【发布时间】:2021-05-17 20:20:37
【问题描述】:
目标
我想遍历一个包含多个对象的数组,其中每个对象定义如下;
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;
}
问题
但是,linter 提示错误消息,说
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 的文档,但解释代码中的对象总是为每个属性提供相同类型的值。但是,在我的例子中,该值具有多种类型,例如单个对象中的数字、字符串和布尔值。
【问题讨论】:
标签: typescript