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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With