In type script I have a union literal type defined as
export type Color =
| 'red'
| 'green'
| 'blue'
| 'teal'
| 'purple'
How can I defined the type of a dictionary whose keys are some of the values of Color and the keys as string?
For instance:
const COLOR_MAP = {
red: 'Cool',
aree: 'Not so cool'
}
How can I typize COLOR_MAP so that I can access its set values with a string whose type is Color?
>Solution :
Use Record<Color, string> or { [key in Color]: string } for an exhaustive map.
Use Partial<Record<Color, string>> or { [key in Color]?: string } for a non-exhaustive map.
If you want some specific subset of the union that is known at compile-time you can use Extract:
Record<Extract<Color, 'red' | 'teal'>, string>