Home > Blockchain >  Typescript: extend a literal type to allow more options
Typescript: extend a literal type to allow more options

Time:01-06

So I have one type that contains a few possible literal values:

type ProductStatusType = 'INACTIVE' | 'ACTIVE' | 'UNKNOWN';

but I'd also need another type that will be exported and will have more options (including the above):

export type ExtendedProductStatusType = 'INACTIVE' | 'ACTIVE' | 'UNKNOWN' | 'NEW_STATUS' | 'ANOTHER_STATUS'

I know that to extend a type one can use the intersection (&) sign but I'm struggling how to make it just another literal option.

Incorrect meta code below:

export type ExtendedProductStatusType = ProductStatusType & { | 'NEW_STATUS' | 'ANOTHER_STATUS' }

Is it even possible?

CodePudding user response:

You just need to create a union between the original union and the new literals:

type ProductStatusType = 'INACTIVE' | 'ACTIVE' | 'UNKNOWN';

// Same as 'INACTIVE' | 'ACTIVE' | 'UNKNOWN' | 'NEW_STATUS' | 'ANOTHER_STATUS'
export type ExtendedProductStatusType = ProductStatusType | 'NEW_STATUS' | 'ANOTHER_STATUS'

Playground Link

Unions of unions are automatically flattened.

  • Related