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

sku*_*ube 7 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;
    });
Run Code Online (Sandbox Code Playgroud)

有人可以帮助破译 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]
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 9

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

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

其错误的原因是因为object无法分配给以下类型的内容MyInterface

interface MyInterface {
  type: string;
}
declare let foo: object;
declare let bar: MyInterface;
// ERROR: object not assignable to MyInterface
bar = foo; 
Run Code Online (Sandbox Code Playgroud)

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

使固定

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

更好的修复

使用确切的类型即 MyInterface

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