Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert type number to type string

Tags:

typescript

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?

like image 744
A. L Avatar asked Aug 26 '26 04:08

A. L


1 Answers

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

like image 151
Boussadjra Brahim Avatar answered Aug 27 '26 18:08

Boussadjra Brahim