首页 > 解决方案 > 类型“T”上不存在属性“id”。(2339)打字稿泛型错误

问题描述

我有一个函数调用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)

以下是此问题的完整环境的 typescript playground 链接,此处错误以红色突出显示:Typescript Playground 中的示例

标签: typescript

解决方案


您需要为您的泛型类型提供一个约束,如下所示:<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[] => {


推荐阅读