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.
CodePudding user response:
let gender: 'male' | 'female';
CodePudding user response:
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.
CodePudding user response:
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