![](/img/trans.png)
[英]VSCode how to fix typescript highlight error Argument of type {} is not assignable to parameter of
[英]typescript fix error argument of type is not assignable
我不知道为什么我遇到了问题。 我有一个接受对象数组的函数。 每个对象都有一个名为id
的属性,我想从给定的数据中获取最后一个id
。 代码工作正常。
type Data = object;
const data = [
{
'id': 1,
'name': 'Uncategorized',
},
{
'id': 2,
'name': 'DSLR Cameras',
},
{
'id': 3,
'name': 'Printer / Ink',
},
];
const getLastId = (data: Data[]): number => {
if (Array.isArray(data) && data.length > 0) {
// Create an array of Id's of all items
const idsArray: number[] = [];
data.forEach((obj: { id: number }) => idsArray.push(obj.id));
// Return last element id
return idsArray[data.length - 1];
} else {
return 1;
}
};
但是,在以下行中,将出现错误。
data.forEach((obj: { id: number }) => idsArray.push(obj.id));
TS2345: Argument of type '(obj: { id: number; }) => number' is not assignable to parameter of type '(value: object, index: number, array: object[]) => void'.
Types of parameters 'obj' and 'value' are incompatible.
Property 'id' is missing in type '{}' but required in type '{ id: number; }'.
这是什么类型的错误以及如何解决这个问题? 关联
你的数据(我不喜欢这个名字)声明是对象,但应该是这样的:
type Data = {
id: number,
name: string,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.