繁体   English   中英

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

[英]How to define an object with different type of value correctly in Typescript

目标

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

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

function 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 的文档,但解释代码中的 object 总是为每个属性提供相同类型的值。 但是,在我的例子中,该值具有多种类型,例如数字、字符串和 boolean 在单个 object 中。

使用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告诉 TS attr将是idtextcomplete之一。

TS游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM