类型“ T”上不存在属性“ id”。(2339)打字稿泛型错误

时间:2020-06-17 20:20:03

标签: typescript

我有一个名为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

1 个答案:

答案 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[] => {