Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I defined the type of a dictionary whose keys are **some** of the values of union literal type?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading