如何在Typescript中正确定义具有不同类型值的对象



目标

我想遍历一个包含多个对象的数组,其中每个对象定义如下;

interface Todo {
id: number;
text:string;
complete:boolean;
}

函数findIndex(array: Todo[], attr:string, value: number | string | boolean)遍历数组,并检查数组的元素是否与给定属性的给定值相同。

const findIndex = (array: Todo[], attr: string, value: number | string | boolean)=>{
for(var i=0; i<array.length; i++) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}

问题

然而,短纤提示错误信息,称

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Todo'.
No index signature with a parameter of type 'string' was found on type 'Todo'.ts(7053)

已尝试

我是打字的新手。我通读了typescript的文档,但解释代码中的对象对于每个属性总是具有相同类型的值。然而,在我的情况下,值有各种类型,例如单个对象中的数字、字符串和布尔值。

使用keyof运算符:

interface Todo {
id: number;
text:string;
complete:boolean;
}
const findIndex = (array: Todo[], attr: keyof Todo, value: number | string | boolean)=>{
for(var i=0; i<array.length; i++) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}

keyof告诉TSattr将是idtextcomplete中的一个。

TS游乐场

最新更新