Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 财产';id';不存在于类型';T';。(2339)类型脚本泛型错误_Typescript - Fatal编程技术网

Typescript 财产';id';不存在于类型';T';。(2339)类型脚本泛型错误

Typescript 财产';id';不存在于类型';T';。(2339)类型脚本泛型错误,typescript,Typescript,我有一个名为updateArrayOfObjects的函数,它更新数组中的对象。我正在向该函数传递一个泛型类型,如下所示: interface OtherIncomeSource { id?: string; incomeDescription?: string; amount?: number; } const otherIncomes = [ { id: "#6523-3244-3423-4343", inco

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

下面是有关此问题的完整环境的typescript链接,在这里,错误以红色突出显示:

您需要为泛型类型提供一个约束,如下所示:

更新行
const updateArrayOfObjects=(arrayOfObjects:T[],newObject:T,deleteObject:boolean=false):T[]=>{


to
const updatearrayofoobjects=(arrayofoobjects:T[],newObject:T,deleteObject:boolean=false):T[]=>{

谢谢,错误消失了。这让我意识到我没有编写真正的泛型函数,因为我在函数中使用了
id
。现在我将
id
作为参数传递给函数,得到了“无索引签名”问题。尝试使此函数真正泛型。
let index = newArrayOfObjects.findIndex((obj: T) => obj.id === newObject.id)