【问题标题】:Argument of type '...' is not assignable to parameter of type '...' TS 2345“...”类型的参数不可分配给“...”类型的参数 TS 2345
【发布时间】:2020-11-26 22:17:55
【问题描述】:

鉴于以下情况:

interface MyInterface {
  type: string;
}

let arr: object[] = [ {type: 'asdf'}, {type: 'qwerty'}]

// Alphabetical sort
arr.sort((a: MyInterface, b: MyInterface) => {
      if (a.type < b.type) return -1;
      if (a.type > b.type) return 1;
      return 0;
    });

谁能帮忙破译TS错误:

// TypeScript Error
[ts]
Argument of type '(a: MyInterface, b: MyInterface) => 0 | 1 | -1' is not assignable to parameter of type '(a: object, b: object) => number'.
  Types of parameters 'a' and 'a' are incompatible.
    Type '{}' is missing the following properties from type 'MyInterface': type [2345]

【问题讨论】:

  • 无法使用发布的代码进行复制。 let arr:object[] 是我可以重现错误的唯一方法..
  • 无法重现该错误。 see this
  • object[] 不等同于显示的对象数组吗?无论如何,我已经更新了原始帖子以包含 arr 的类型
  • 不,不是。如果你省略类型,TS 会推断它,所以arr 的类型将是{type: string;}[],你不会得到错误。如果将其设置为object,则会收到错误,因为回调的参数与object 不兼容。
  • 小心:它是let arr: MyInterface[]。否则,它是 Typescript 中的元组

标签: typescript


【解决方案1】:

这是一个重现错误的简化示例:

interface MyInterface {
  type: string;
}
let arr:object[] = []
// Error: "object" is not compatible with MyInterface 
arr.sort((a: MyInterface, b: MyInterface) => {});

它出错的原因是因为object 不能分配给MyInterface 类型的东西:

interface MyInterface {
  type: string;
}
declare let foo: object;
declare let bar: MyInterface;
// ERROR: object not assignable to MyInterface
bar = foo; 

这是一个错误的原因是因为object{} 的同义词。 {} 没有 type 属性,因此与 MyInterface 不兼容。

修复

也许您打算使用any(而不是object)。 any一切兼容。

更好的修复

使用确切的类型,即MyInterface

interface MyInterface {
  type: string;
}
let arr:MyInterface[] = []; // Add correct annotation ?
arr.sort((a: MyInterface, b: MyInterface) => {});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多