Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
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 Respuestas
Responde la pregunta

0

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

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda