I have a simple type:
type person = 'man' | 'woman'
and I have an input string x
.
How may I check whether it is a person
or not?
I have a simple type:
type person = 'man' | 'woman'
and I have an input string x
.
How may I check whether it is a person
or not?
Since TypeScript types are merely a compile-time construct, there is no built in way to check that x
is a person
. However, you can write your own type narrowing function that does the equivalent:
function isPerson(x: string): x is person {
return x == 'man' || x == 'woman'
}
When using this function, TypeScript will automatically narrow down the type for you, e.g.:
function funcThatTakesAPerson(p: person) {
//...
}
function funcThatTakesAString(x: string) {
funcThatTakesAPerson(x); // compile error; x is a string, not a person
if (isPerson(x)) {
funcThatTakesAPerson(x); // works; TypeScript knows that x is a person
}
}