我有一个名为 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
时,我在下面提到的行中遇到错误说“属性 'id' 在类型 'T' 上不存在。(2339)”:let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)
以下是此问题完整环境的 typescript 操场链接,此处错误以红色突出显示:Example in Typescript Playground
最佳答案
您需要为您的泛型类型提供如下约束:<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[] => {
关于typescript - 属性 'id' 在类型 'T' 上不存在。(2339)Typescript 泛型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62437690/