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:

alert(y.toString());

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

if (y instanceof SomeClass) {
  SomeClass.someFunction();      
}

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

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