Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Number type to custom type of number

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a type assertion like this:

const value = Math.floor(Math.random() * 6) as CustomType;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda