Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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 answers
Answer question

0

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

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!