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:

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

So is completely valid to call this function like this:

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 :)

Pedro Luz
A personal blog by Pedro Luz about coding, coding, habit building, and a few things more.(Psst... I am open to opportunities.)
Reach out to me on your favorite social :)© 2020 Pedro Luz