![](/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.