How do I narrow a union of string and Regex?

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.


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