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

233
Visualizações
How to have a variable to take one of some predefined values in typescript?

I have a variable lets say gender. I am declaring it in beginning and assigning a value later in the code. I want to restrict the value of gender to be either male or female. Anything other than this should not be accepted (throw an error). Is there a way in typescript to do this?

let gender: string;

// some logic here

gender = someFunction();  //Restrict this to only accept 'male' and 'female' as valid values.
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

let gender: 'male' | 'female';
about 4 years ago · Juan Pablo Isaza Relatório

0

Using Enum

What you can do is to define an enum, and let the return type of your function be that enum. The same goes for your gender variable. It can be of type Gender instead of string.

enum Gender {male, female};

let gender: Gender;

function someFunction(): Gender {
  return Gender.male;
}

// some logic here

gender = someFunction();  //Restrict this to only accept 'male' and 'female' as valid values.

Using Union Type

As others have mention in their answers, you can also use a union type. The function also needs to return the same union type.

let gender: "male" | "female";

function someFunction(): "male" | "female" {
  return "male";
}

// some logic here

gender = someFunction();  //Restrict this to only accept 'male' and 'female' as valid values.
about 4 years ago · Juan Pablo Isaza Relatório

0

At the variable or constant declaration, you can define the strings it can have, for example

let gender: "male" | "female" | "other";

You can do the same for typescript interfaces

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