Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this number type ? (TypeScript)

const arr = [1, 2, 3, 4] as const;
type Arr = typeof arr[number];
// expected & result type : 1 | 2 | 3 | 4

const doubledArr = arr.map(el => el * 2);
type DoubledArr = typeof doubledArr[number];
// expected type : 2 | 4 | 6 | 8
// result type : number

I expected DoubledArr type as 2 | 4 | 6 | 8 by arr.
But the DoubleArr type came out as the number.
How can I get the DoubledArr type as 2 | 4 | 6 | 8.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That sort of a mathematical transformation isn’t something typescript can figure out statically. If you want that to be the resulting type, you will need to assert it:

const doubledArr = arr.map((el) => el * 2 as 2 | 4 | 6 | 8 );
// OR:
const doubledArr = arr.map((el) => el * 2) as (2 | 4 | 6 | 8)[];

Keep in mind that type assertions are basically a way to tell typescript "i know better then you, so don’t check my work here". If you make a mistake with the assertion, typescript won’t be able to warn you about it (unless it’s an extremely obvious mistake)

If this feature request ever got implemented it might include those capabilities, but i wouldn’t expect that any time soon.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading