Typescript: union type example

In Typescript, a type can be one of a list of types. This is a pretty novel feature that is necessary to support Javascript – I can’t think of any mainstream languages that support something like this.

For instance, the following code would be valid:

let x : string | number;

x = 1;
x = '1';

Anything that is common (assume duck-typing) can be called on the item:

console.log(x.toString());

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

if (x instanceof String) {
  ...      
}

If you want to use primitives, you have to use the typeof from Javascript:

if (typeof x === "number") {
  ...
}

if (typeof x === "string") {
  ...     
}

While this looks hokey, it is quite magical – the use of “if” around the code in question causes an implicit cast:

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