gpt4 book ai didi

typescript - '...' 类型的参数不能分配给 '...' 类型的参数 TS 2345

转载 作者:行者123 更新时间:2023-12-04 10:52:36 25 4
gpt4 key购买 nike

鉴于以下情况:

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]

最佳答案

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

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

关于typescript - '...' 类型的参数不能分配给 '...' 类型的参数 TS 2345,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54298051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com