"strictNullChecks"

Treats null and undefined as separate types, forcing you to handle them.

On this page

Example

#
TypeScript
const scores = new Map([['ania', 92]])

const kuba = scores.get('kuba')
// const kuba: number | undefined

console.log(kuba ?? 'no score')
console.log(scores.get('ania')?.toFixed(1))
Result
no score
92.0

Definition and usage

#

With strictNullChecks on, the values null and undefined don’t fit into other types. If something can be empty, that has to be in its type (string | null), and you have to check it before use.

Without this option, the compiler lets you assign null to any variable and doesn’t warn you about reading a property from an empty value. Then “Cannot read properties of null” errors only surface for your users.

It’s one of the most valuable checks, and part of strict mode. It forces you to handle edge cases: a missing element on the page, a missing user, or an empty search result.

Syntax

#
Syntax
"strictNullChecks": true

More examples

#
An error without a check
TypeScript
const button = document.querySelector('button')
button.addEventListener('click', () => {})
// Error: 'button' is possibly 'null'.

Good practices

#
  • Don’t turn off strictNullChecks. It protects against the most common kind of bug in JavaScript.
  • Handle the empty value with ?. and ?? or an early return, and leave the ! assertion for exceptional situations.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.