lundi 8 juin 2020

Interfacing Random Numbers in Typescript

I have a type

type DiceNumber = 1 | 2 | 3 | 4 | 5 | 6

for part of a react state. I want to set the state to a random number between 1 and 6, so I try this

const dice = Math.floor(Math.random() * 6) + 1;

but I get

Type 'number' is not assignable to type 'DiceNumber'.

I understand why, but is there a way around this? Can I guarantee random numbers to fit the type?




Aucun commentaire:

Enregistrer un commentaire