TS2536: Type cannot be used to index type ENUM - TS MAPPED TYPES

Viewed 1218

To use my color enum in my theme, I have to declare its type.
I tried this:

enum COLORS {
  PRIMARY = '#FF7900',
}

type ColorsType = {
  [key in keyof typeof COLORS]: COLORS[key] // error
}

interface ThemeColors extends ColorsType {}

But I'm getting this error: TS2536: Type 'key' cannot be used to index type 'COLORS'

It's working if I use string instead of COLORS[key], but I don't want the type to allow any string for any COLORS property.

How do we force keys to equal their values with a mapped type of enum?

1 Answers

The value type should actually be (typeof COLORS)[key].

enum COLORS {
  PRIMARY = '#FF7900',
  SECONDARY = '#FFFFFF',
}

type ColorsType = {
  [key in keyof typeof COLORS]?: typeof COLORS[key];
  // if not optional, all COLORS enum keys are required!
}

// These might be what you want
var colors: ColorsType = { PRIMARY: COLORS.PRIMARY }; // OK
var wrongColors: ColorsType = { PRIMARY: COLORS.SECONDARY }; // error!

EDIT: The solution can be further simplified to:

type ColorsType = Partial<typeof COLORS>;
Related