1

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • At runtime? The types have been erased. – jonrsharpe Mar 28 '22 at 15:17
  • 2
    `const persons = ['man', 'woman'] as const; type Person = (typeof persons)[number]; const isPerson = persons.includes(x);`. – Clashsoft Mar 28 '22 at 15:19
  • As @jonrsharpe mentioned, types are erased at runtime but as @clashsoft mentioned, if the string is 'man' or 'woman', then it is a `person`, non-binary definitions non-withstanding. – Ruan Mendes Mar 28 '22 at 15:22
  • At runtime your Typescript wouldn't exist - it would have been compiled to Javascript, so you would need to perform some logic on the object you are checking the type of, with something like the typeof operator. – Jeremy Mar 28 '22 at 15:26
  • What of the `instanceof` operator e.g. `person instanceof Man;` where Man is the class. It should return a boolean for you to work with. Take a look at this answer for more detail on the operator https://stackoverflow.com/a/12789324/8252265 – peterpie Mar 28 '22 at 16:03

1 Answers1

2

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
   }
}
David Deutsch
  • 17,443
  • 4
  • 47
  • 54