Static typing key: value of an object while defining

Ideally, want to statically type the keys and values in THEMES object in compile time. Currently, keys are of type "string", which I don't want. export type THEMES_CLASSES = | "light-yellow" | "dark" | "light-green" | "light-blue"; export const THEMES: { any: THEMES_CLASSES } = { LIGHT_YELLOW: "light-yellow", LIGHT_GREEN: "light-green", LIGHT_BLUE: "light-blue", DARK: "dark", }; Any help is much appreciated blessjmg
5 Replies
JulieCezar
JulieCezar2y ago
Using the satisfies operator: type THEMES_CLASSES = | "light-yellow" | "dark" | "light-green" | "light-blue" export const THEMES = { LIGHT_YELLOW: "light-yellow", LIGHT_GREEN: "light-green", LIGHT_BLUE: "light-blue", DARK: "dark", } satisfies { [key: string]: THEMES_CLASSES }
~Abhinav
~Abhinav2y ago
Got it, thanks. I want to do the same thing for mapping THEME_CLASSES to their respective string color values like this export const ThemeColors = { "light-yellow": "#fde68a", "light-green": "#bbf7d0", "light-blue": "#bae6fd", dark: "#44403c", } satisfies { [key: THEMES_CLASSES]: string }; but its giving this error for "key" - "An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead." Any ideas?
Brendonovich
Brendonovich2y ago
You should be able to change the satisfies clause to { [Key in THEMES_CLASSES]: string } to make it a mapped type
~Abhinav
~Abhinav2y ago
Got it, working now. Thanks alot for your help @JulieCezar @Brendonovich
JulieCezar
JulieCezar2y ago
I tried smth like that too, but forgot about the in xD
Want results from more Discord servers?
Add your server