Topsy
Topsy

Reputation: 1162

Generate a string array from a union type typescript

Hi guys I am looking for a way to get an array from a union typescript type

This is an existing type :

 export type GridClassKey =
  | 'root'
  | 'container'
  | 'item'
  | 'zeroMinWidth'
  | 'direction-xs-column'
  | 'direction-xs-column-reverse'
  | 'direction-xs-row-reverse'
  | 'wrap-xs-nowrap'
  | 'wrap-xs-wrap-reverse'
  | 'align-items-xs-center'
  | 'align-items-xs-flex-start'
  | 'align-items-xs-flex-end'
  | 'align-items-xs-baseline'
  | 'align-content-xs-center'
  | 'align-content-xs-flex-start'
  | 'align-content-xs-flex-end'
  | 'align-content-xs-space-between'
  | 'align-content-xs-space-around'
  | 'justify-xs-center'
  | 'justify-xs-flex-end'
  | 'justify-xs-space-between'
  | 'justify-xs-space-around'
  | 'justify-xs-space-evenly'
  | 'spacing-xs-1'
  | 'spacing-xs-2'
  | 'spacing-xs-3'
  | 'spacing-xs-4'
  | 'spacing-xs-5'
  | 'spacing-xs-6'
  | 'spacing-xs-7'
  | 'spacing-xs-8'
  | 'spacing-xs-9'
  | 'spacing-xs-10'
  | 'grid-xs-auto'
  | 'grid-xs-true'
  | 'grid-xs-1'
  | 'grid-xs-2'
  | 'grid-xs-3'
  | 'grid-xs-4'
  | 'grid-xs-5'
  | 'grid-xs-6'
  | 'grid-xs-7'
  | 'grid-xs-8'
  | 'grid-xs-9'
  | 'grid-xs-10'
  | 'grid-xs-11'
  | 'grid-xs-12'

I would like to get programmatically a real string array from it, something like :

['root','container', ...]

is it possible, since GridClassKey is a type and not a value ?

Thank you

Upvotes: 16

Views: 9800

Answers (1)

Shivam Singla
Shivam Singla

Reputation: 2201

There is no way that we can create an array from the type because we cannot assemble an array at runtime if types don't exist at runtime (@Ingo Bürk's comment). But we can do the reverse. If we have a const array, we can get a union type for it. For example-

const gridClassKeys = ['root', 'container'] as const

// "root" | "container"
type GridClassKey = typeof gridClassKeys[number]

Playground

Please note, we have to use const assertions while declaring the array (the array will be readlonly tuple, therefore fixed keys)

Upvotes: 20

Related Questions