Home > other >  Why is this number type ? (TypeScript)
Why is this number type ? (TypeScript)

Time:03-29

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.

CodePudding user response:

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.

  • Related