给出以下内容:
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]
答案 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) => {});