【问题标题】:Using TypeScript Enum as object property keys使用 TypeScript 枚举作为对象属性键
【发布时间】:2022-09-23 10:47:00
【问题描述】:

我正在尝试使用枚举值作为对象的键,希望在获取值时保留类型,但我得到Element implicitly has an \'any\' type because expression of type \'string\' can\'t be used to index type

export enum TaskType {
  Classification = \'classification\',
  Extraction = \'extraction\'
}
const comparisons: { [name in TaskType]: Function } = {
  \'classification\': () => false,
  \'extraction\': () => false
}
for (const taskType in comparisons) {
  // I expect func to be of type Function, but I get a TypeScript error:
  // Element implicitly has an \'any\' type because expression of type \'string\' can\'t be used to index type
  const func = comparisons[taskType] 
}

我尝试过使用const func = comparisons[taskType as keyof TaskType],但这也不起作用。

    标签: typescript


    【解决方案1】:

    for-in 中的taskType 是字符串类型,不能将其映射到comparisons 下的枚举类型。

    您可以通过as 将其转换为TaskType 枚举,如下所示

    旁注,您可以直接在其上使用枚举键,而不是为comparisons 使用静态字符串键。

    export enum TaskType {
      Classification = 'classification',
      Extraction = 'extraction'
    }
    const comparisons: { [name in TaskType]: Function } = {
      [TaskType.Classification]: () => false,
      [TaskType.Extraction]: () => false
    }
    for (const taskType in comparisons) {
      const func = comparisons[taskType as TaskType] //cast it to an enum type
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 2019-02-17
      • 2023-04-04
      • 2017-05-01
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多