【问题标题】:How to define an object with different type of value correctly in Typescript如何在 Typescript 中正确定义具有不同类型值的对象
【发布时间】: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


    【解决方案1】:

    使用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 playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2021-07-16
      • 2015-02-05
      • 2016-12-02
      相关资源
      最近更新 更多