Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert typescript types of strings to array of strings?

I've this type:

type myCustomType = "aaa" | "bbb" | "ccc"; 

I need to convert it to an array like this:

["aaa", "bbb", "ccc"] 

How can I do this in typescript?

like image 834
Diemauerdk Avatar asked Jan 22 '20 10:01

Diemauerdk


People also ask

Can you convert a string to an array?

We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.

How do you convert an array into string literal union type in TypeScript?

To convert an array of strings into a string literal union type in TypeScript, you can first define the array of strings then make the array as readonly using the as const keyword, and then use the typeof operator on all the values contained in the array.

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.


1 Answers

Types do not exist in emitted code - you can't go from a type to an array.

But you could go the other way around, in some situations. If the array is not dynamic (or its values can be completely determined by the type-checker at the time it's initialized), you can declare the array as const (so that the array's type is ["aaa", "bbb", "ccc"] rather than string[]), and then create a type from it by mapping its values from arr[number]:

const arr = ["aaa", "bbb", "ccc"] as const; type myCustomType = typeof arr[number]; 

Here's an example on the playground.

like image 69
CertainPerformance Avatar answered Sep 18 '22 18:09

CertainPerformance