1

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.

0kMike
  • 124
  • 1
  • 9
  • Does this answer your question? [Typescript Type 'string' is not assignable to type](https://stackoverflow.com/questions/37978528/typescript-type-string-is-not-assignable-to-type) – outis Oct 05 '21 at 12:10

1 Answers1

2

You can use a type assertion like this:

const value = Math.floor(Math.random() * 6) as CustomType;
H.B.
  • 166,899
  • 29
  • 327
  • 400