【发布时间】: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