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?
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.
arr[0], arr[1], etc; arr[someNumber] where someNumber is a number. It's TypeScript syntax only, not JS.as const part?string[], and instead keeps it as a static tuple of ["aaa", "bbb", "ccc"]const and the type with the same name. When you import it as a type, TypeScript ensures you cannot use it as a regular array. When you import it as a regular array, TypeScript correctly identifies where it is used as a type and where it is used as a regular array.Here is a way of doing this using an intermediary, "throwaway" object, which the compiler will ensure must contain exactly all the possible type values (no more or less):
type myCustomType = "aaa" | "bbb" | "ccc";
const myCustomTypeObject: {
[key in myCustomType]: undefined;
} = { aaa: undefined, bbb: undefined, ccc: undefined };
const myCustomTypeArray = Object.keys(myCustomTypeObject);
UPDATE: Here is a slightly longer version, which tidies up by setting the intermediary object to undefined afterwards since it is unlikely to be needed again.
type myCustomType = "aaa" | "bbb" | "ccc";
let tempMyCustomTypeObject:
| {
[key in myCustomType]: undefined;
}
| undefined = { aaa: undefined, bbb: undefined, ccc: undefined };
const myCustomTypeArray = Object.keys(tempMyCustomTypeObject);
tempMyCustomTypeObject = undefined;
myCustomTypeArray exactly aligns with myCustomType - if you just convert manually without this code, there would be no compiler error if you missed something or e.g. the type was changed by another developer later.
const arr = ["aaa", "bbb", "ccc"] as const; type arrTypes = typeof arr[number];as constpart. I think that would be a good answer, I suggest posting it.