17

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

2
  • 2
    No, it's not, because you cannot assemble an array at runtime if types don't exist at runtime. Commented Mar 22, 2021 at 17:34
  • I remember seeing an NPM library that generated files with arrays based on types exactly like this. I can't find it now though. I wish I could. Commented Mar 8, 2023 at 0:49

1 Answer 1

20

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, unfortunately I only have these types as data source :/ too bad... Thanks for the answer !
@Topsy If the types are in a file, you can do file manipulation to retrieve the array.
It's a typescript file from material ui node modules ^^ So I don't really want to do that. But it's ok I did it manually ^^thanks
@Topsy, yeh, that will not be a good idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.