Home > OS >  I have a question regarding union type in TypeScript
I have a question regarding union type in TypeScript

Time:11-18

I created my own type using numbers. But, it didn't work.

This is the code for reproducing the issue.

import _ from 'lodash';

type ANGLE = 0 | 90 | 180 | 270;

function test(angle: ANGLE) {
  console.log(angle)
}

test(_.shuffle([0, 90, 180, 270])[0])

But, I got an error.

error TS2345: Argument of type 'number' is not assignable to parameter of type 'ANGLE'.

I have no idea about this. I thought it is not a problem because I used number both parameter type and argument type.

Please help me out.

CodePudding user response:

By default an array literal of numbers is widened to number and the original number literal types are not preserved (so the types of the array elements are all converted to number basically)

You can use an as const assertion. This will make the compiler infer a readonly tuple from the array literal, and more importantly in this case, it will also preserver the array literal types:

import _ from 'lodash';

type ANGLE = 0 | 90 | 180 | 270;

function test(angle: ANGLE) {
  console.log(angle)
}

test(_.shuffle([0, 90, 180, 270] as const)[0])

Playground Link

  • Related