【问题标题】:How to access Enum in typescript ? giving error "Element implicitly has an any type because index expression is not of type number"如何在打字稿中访问枚举?给出错误“元素隐式具有任何类型,因为索引表达式不是数字类型”
【发布时间】:2021-04-19 15:54:08
【问题描述】:
export enum r {
  color1 = "Red"
  color2 = "green"
  color3 = "blue"
}

ar = ["color1", "color2"];
ar.map(e => {
  if (r[e as any] !== undefined) {
    return r[e]
  }
})

上面的语句给出“元素隐式具有任何类型,因为索引表达式不是数字类型”

【问题讨论】:

    标签: javascript typescript react-native enums


    【解决方案1】:

    您需要输入 arkeyof typeof 以让 TypeScript 知道您的数组包含来自枚举的值:

    export enum r {
      color1 = "Red",
      color2 = "green",
      color3 = "blue",
    }
    
    const ar: (keyof typeof r)[] = ["color1", "color2"];
    const newVal = ar.map((e) => {
      if (r[e] !== undefined) {
        return r[e];
      }
    });
    

    这里有一个很好的深入answer 介绍

    【讨论】:

      【解决方案2】:

      枚举中的每个项目后都没有逗号。但是,以下是如何将参数类型转换为枚举键的类型:

      export enum r {
      color1 = "Red",
      color2 = "green",
      color3 = "blue",
      }
      
      const ar = ["color1","color2"];
      const new_ar = ar.filter(e => {
          if (e in r && r[e as keyof typeof r]) 
          {return true;}
          else {return false;}
      })
      

      您的方法的问题是您正在使用 map 并且您需要在每次迭代中返回。你需要的是过滤器。

      【讨论】:

        猜你喜欢
        • 2018-05-31
        • 2018-04-25
        • 2021-04-23
        • 2022-06-12
        • 2023-04-01
        • 2022-09-23
        • 2021-10-11
        • 2017-03-14
        • 2021-08-01
        相关资源
        最近更新 更多