Typescript 财产';id';不存在于类型';T';。(2339)类型脚本泛型错误
我有一个名为Typescript 财产';id';不存在于类型';T';。(2339)类型脚本泛型错误,typescript,Typescript,我有一个名为updateArrayOfObjects的函数,它更新数组中的对象。我正在向该函数传递一个泛型类型,如下所示: interface OtherIncomeSource { id?: string; incomeDescription?: string; amount?: number; } const otherIncomes = [ { id: "#6523-3244-3423-4343", inco
updateArrayOfObjects
的函数,它更新数组中的对象。我正在向该函数传递一个泛型类型,如下所示:
interface OtherIncomeSource {
id?: string;
incomeDescription?: string;
amount?: number;
}
const otherIncomes = [
{
id: "#6523-3244-3423-4343",
incomeDescription: "Rent",
amount: 100
},
{
id: "#6523-3244-3423-4343",
incomeDescription: "Commercial",
amount: undefined
}
]
const updateArrayOfObjects = <T>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
const newArrayOfObjects = arrayOfObjects.slice();
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)
if(deleteObject) {
newArrayOfObjects.splice(index, 1);
} else {
if (index === -1) {
newArrayOfObjects.push(newObject);
} else {
newArrayOfObjects[index] = newObject;
}
}
return newArrayOfObjects
}
const newData = updateArrayOfObjects<OtherIncomeSource>(otherIncomes, {id: '1233', incomeDescription: 'agri', amount: 5000})
下面是有关此问题的完整环境的typescript链接,在这里,错误以红色突出显示:您需要为泛型类型提供一个约束,如下所示:
更新行const updateArrayOfObjects=(arrayOfObjects:T[],newObject:T,deleteObject:boolean=false):T[]=>{
to
const updatearrayofoobjects=(arrayofoobjects:T[],newObject:T,deleteObject:boolean=false):T[]=>{
谢谢,错误消失了。这让我意识到我没有编写真正的泛型函数,因为我在函数中使用了id
。现在我将id
作为参数传递给函数,得到了“无索引签名”问题。尝试使此函数真正泛型。
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)