[英]Property 'id' does not exist on type 'T'.(2339) Typescript Generics error
I have a function called updateArrayOfObjects
which updates the object in the array.我有一个名为
updateArrayOfObjects
的 function ,它更新数组中的 object 。 I am passing a generic type to this function like below:我将一个泛型类型传递给这个 function,如下所示:
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})
I am getting an error at the below mentioned line when accessing id
saying "Property 'id' does not exist on type 'T'.(2339)":访问
id
时,我在下面提到的行出现错误,说“类型 'T' 上不存在属性 'id'。(2339)”:
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)
Below is the typescript playground link for a complete environment of this issue and in here the error is highlighted in red: Example in Typescript Playground以下是此问题的完整环境的 typescript 操场链接,此处错误以红色突出显示: Typescript 操场中的示例
You need to provide a constraint for your generic type as follows: <T extends { id?: string }>
您需要为泛型类型提供如下约束:
<T extends { id?: string }>
Update the line const updateArrayOfObjects = <T>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
更新行
const updateArrayOfObjects = <T>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
to const updateArrayOfObjects = <T extends { id?: string }>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
to
const updateArrayOfObjects = <T extends { id?: string }>(arrayOfObjects: T[], newObject: T, deleteObject: boolean = false): T[] => {
I had a more complex case where the above answer didn't work for me.我有一个更复杂的情况,上面的答案对我不起作用。
This is what worked for me:这对我有用:
type SimpleTableProps<T> = {
data: Array<T & { id?: number }>;
...
};
const SimpleTable = <T,>(props: SimpleTableProps<T>): JSX.Element => {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.