adplus-dvertising

Using TypeScript Enum as object property keys

Asked 2 days ago
Viewed 6 times

I'm trying to use Enum values as the keys for an object, expecting this to preserve the type when I get the value, but I'm getting 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] 
}

I've tried using const func = comparisons[taskType as keyof TaskType] but this doesn't work either.

asked 2 days ago

Correct Answer

taskType in for-in is a string type, you cannot map it with an enum type under comparisons.

You can cast it to TaskType enum by as like below

Side note, instead of using a static string key for comparisons, you can use enum keys directly on it.

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

answered 2 days ago