Typescript, undefined and null

Typescript, undefined and null

In Typescript, undefined and null are sub-types of any other type (string, boolean, number, void), which means that you can use undefined or null to replace any other type.

With this example:

1
2
3
function sum(a: number, b: number): number {
  return a + b
}

So is completely valid to call this function like this:

5
sum(undefined, null) // <-- valid

But after Typescript 2.0, we can tell Typescript to treat undefined and null like separated types. We can do this by enabling "strictNullChecks": true in tsconfig.json.

1
2
3
4
5
{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

With this enabled the sum(undefined, null) will not be valid anymore.

How easy is that :)