Skip to content
Advertisement

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):

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;

Advertisement

Answer

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

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

Playground

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement