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?
You can't do it with string literal but you can do it with an enum
enum MyEnum {
"aaa",
"bbb",
"ccc",
}
Object.keys(MyEnum).forEach(key => {
console.log(key);
})
Repro here : https://stackblitz.com/edit/typescript-uqvach
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.
For example:
const themeMode = ['light', 'dark'] as const;
type MainTheme = typeof themeMode[number];
const values = [...themeMode];
// iterate on themeMode as const assertion
values.map((theme) => console.log(theme));