Home > database >  Number type to custom type of number
Number type to custom type of number

Time:10-06

I created a simple type:

export type CustomType = 0 | 1 | 2 | 3 | 4 | 5;

Now I want to initialize an already declared variable (current value = 0) of this type with the result of

Math.floor(Math.random() * 6)

Now, TypeScript tells me, that the Type number is not assignable to Type CustomType, even though the initialization should work as long the number is a whole number of 0, 1, 2, 3, 4, or 5.:

TS2322: Type 'number' is not assignable to type 'CustomType'.

Unfortunately, I failed to find any solution thus far. Casting to standard types is fine, but I am unsure how to make my custom type accept a number. Thank you in advance.

CodePudding user response:

You can use a type assertion like this:

const value = Math.floor(Math.random() * 6) as CustomType;
  • Related