类型“ ...”的参数不能分配给类型“ ...”的参数TS 2345

时间:2019-01-21 21:33:08

标签: typescript

给出以下内容:

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]

1 个答案:

答案 0 :(得分:0)

以下是重现该错误的简化示例:

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) => {});