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.
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>;