我有一个名为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})
访问id
时说“属性'T'不存在属性'id'。(2339)“,在下面提到的行上出现错误:
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)
下面是此问题的完整环境的打字机游乐场链接,在此错误以红色突出显示:Example in Typescript Playground
答案 0 :(得分:0)
您需要为通用类型提供一个约束,如下所示:<T extends { id?: string }>
更新第const updateArrayOfObjects = <T>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
行
到const updateArrayOfObjects = <T extends { id?: string }>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {