TypeScripttsconfig options
"strictNullChecks"
Treats null and undefined as separate types, forcing you to handle them.
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": trueMore examples
#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 earlyreturn, and leave the!assertion for exceptional situations.
Related entries
#- "strict"Turns on a set of the most important, rigorous compiler checks.
- null and undefinedThe types for the absence of a value, controlled by strictNullChecks.
- Non-null assertion (!)An exclamation mark after an expression removes null and undefined from the type without checking.
- Type narrowingDetermining a more precise type for a value based on checks in your code.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.