Typescript: OR type example

In Typescript, you may see a variable declared with a pipe – this looks like an “or” in Javascript. These are termed “union types”:

let y : string | number | SomeClass;
y = 7;
y = 'abcdef';
y = new SomeClass();

This is a pretty neat feature. Any common functions are available (e.g. toString). The TypeScript type system uses Duck Typing to establish coherence between types:


If you use non-primitive types, you can use instanceof, like you would in Java or C#:

if (y instanceof SomeClass) {

For primitive detection, you can do a cast and a type check simultaneously:

if (typeof x === "number") {
  console.log(x + 1;

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *