Coverting typescript string literal types to an array of string

Viewed 6260

I have

type ImageVerticalSpacing = 'ignoreBottom' | 'ignoreTop' | 'ignoreBoth' 
| 'Default';

in typescript and need to pass those strings as an array of strings to a dropdown. How can I convert type ImageVerticalSpacing to an array of strings?

3 Answers

Building on top of jcal's answer and reiterating: "You can't convert types in TypeScript to values at runtime. But you can do the reverse: create a runtime object and have TypeScript infer its type." There is a great blog post by @steve-holgado to use const assertions for this purpose: https://steveholgado.com/typescript-types-from-arrays/

With typescript's const assertions (TypeScript 3.4+) you can do:

const animals = ['cat', 'dog', 'mouse'] as const
type Animal = typeof animals[number]

// type Animal = 'cat' | 'dog' | 'mouse'

So the question's code would look like:

const imageVerticalSpacing = ['ignoreBottom', 'ignoreTop', 'ignoreBoth', 'Default'];
type ImageVerticalSpacing = typeof imageVerticalSpacing[number];
Related