How do I narrow a union of string and Regex?

0

Issue

If I define a type like this: type Name = string | Regex and pass it into a function, what is the TypeScript way to discover which type was passed?

It’s easy to find answers to this for JavaScript, but I’m struggling any for TypeScript. Maybe that’s because the answers are one and the same, but I’m hoping there is a compile-time way of checking.

Solution

Typescript doesn’t have any special ways to narrow down types. You need to use regular javascript to narrow down the types, and if you do typescript will deduce that inside if statements (and other control statements), the type can only be one possible type.

So to check whether something is a string you can use typeof foo === "string", and to check for a regular expression you can check for foo instanceof RegExp.

type Name = string | RegExp;

const test: Name = Math.random() > 0.5 ? 'hi' : /ab+c/;

if (typeof test === 'string') {
  console.log(test.toUpperCase());
}

if (test instanceof RegExp) {
  console.log(test.flags);
}

Playground link

Answered By – Nicholas Tower

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More