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.

So this is completely valid:

function sum(a: number, b: number): number {
  return a + b

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.

  "compilerOptions": {
    "strictNullChecks": true

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

How easy is that :)

Share Comments
comments powered by Disqus