If I have an array of numbers, but want to change the types so it's an array of strings (with the same values), how should I go about this?
const a = [
1,
2,
3
] as const
type k = Array<typeof a[number]> // want this to become `("1" | "2" | "3")[]`
How do I change it so that it's an array of strings?
Create a utility type that maps the Array keys and convert their values type to the const string array type :
const a = [
1,
2,
3
] as const;
type ConverToConstStringArray<T extends readonly number[]> = {
[K in keyof T]: `${T[K]}`;
};
type strArr = ConverToConstStringArray<typeof a>;
Or use the infer and convert the numbers to strings recursively :
type ConverToConstStringArray<T extends readonly number[]> =
T extends readonly [infer A, ...infer B]? [`${A}`, ...ConverToConstStringArray<B>]: [];
Playground link
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