`strictNullChecks` is a TypeScript compiler option that stops `null` and `undefined` from being assigned to types that do not include them. It is also enabled by the `strict` setting. Without it, a nullable value can pass a type check and cause surprising JavaScript behavior at runtime. section 7.7.1 section 8.2.2
Listing 7.32 Enabling strict null checks in the tsconfig.json file in the types folder
{
"compilerOptions": {
"target": "ES2022",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}
Set `"strictNullChecks": true` under `compilerOptions` in `tsconfig.json`. section 7.7.1
Make a nullable result explicit
If `calculateTax` can return `null`, a result type of `string | number` produces an error. Include `null` in the union, then check it before treating the result as a number or string: function calculateTax(amount: number): number | null { return amount === 0 ? null : amount * 1.2; } const taxValue = calculateTax(0); if (taxValue === null) { console.log("Value is null"); } else { console.log(taxValue.toFixed(2)); } An explicit value check matters: JavaScript’s `typeof null` is `"object"`. section 7.7.1
The option also exposes nullable values in other familiar code:
- A `null` argument is rejected for a `number` parameter. If null is valid, annotate the parameter `number | null` and guard it before arithmetic; otherwise, JavaScript multiplication can silently coerce null to zero. section 8.2.2
- An optional method may be `undefined`. Check that it exists before invoking it; the compiler otherwise reports that the object is possibly undefined. section 10.2.2
- A variable used before assignment produces an error. A definite assignment assertion (`let value!: number`) can suppress it when assignment is invisible to the compiler, but the assignment remains your responsibility. section 7.7.4
- An empty array may be inferred as `never[]` under this configuration, preventing values from being added. Give the array an explicit type or initialize it with values that establish its type. section 9.2.3
