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 conditionally add several values to a type?

I have this type:

export type SupportedSourceLanguages =
  | LanguageISOCode.En
  | LanguageISOCode.Es
  | LanguageISOCode.Pt
  | LanguageISOCode.De
  | LanguageISOCode.Ko
  | LanguageISOCode.It;

I don’t want those last two to be in the type when a condition is met. How can I conditionally add those last two values only when the condition is met?

This was my approach (but it’s not working):

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 environment = 'production'; 

type LiveSupportedSourceLanguages =
  | LanguageISOCode.En
  | LanguageISOCode.Es
  | LanguageISOCode.Pt
  | LanguageISOCode.De;

type DevSupportedSourceLanguages =
  | LanguageISOCode.Ko
  | LanguageISOCode.It;

export type SupportedSourceLanguages = LiveSupportedSourceLanguages extends environment === 'production' ? DevSupportedSourceLanguages : never;

>Solution :

You need to check if const’s type extends 'production':

export type SupportedSourceLanguages = typeof environment extends 'production' 
  ? LiveSupportedSourceLanguages 
  : DevSupportedSourceLanguages;

Playground

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