Sub topic 8
strictNullChecks: Handling `null` and `undefined`
This chapter assumes you know TypeScript union types, functions, and how to run tsc. You will learn how strictNullChecks prevents code from using a value before checking that it exists.
What `strictNullChecks` changes
With strictNullChecks enabled, null and undefined are separate types. A string variable cannot contain null unless its type says so:
let name: string = "Mina";
// name = null; // Error
let nickname: string | null = null;
nickname = "M";The | symbol creates a union type. string | null means the value is either a string or null.
The strict umbrella option enables strictNullChecks:
{
"compilerOptions": {
"strict": true
}
}You can also enable it directly:
{
"compilerOptions": {
"strictNullChecks": true
}
}Narrowing before use
A value with a nullable type cannot be used as though it were always present. Check the value first. TypeScript then narrows the type inside the checked branch.
function lengthOf(text: string | null): number {
return text === null ? 0 : text.length;
}
console.log(lengthOf("TypeScript")); // 10
console.log(lengthOf(null)); // 0After text === null is false, TypeScript knows that text is a string.
You can use the same pattern for undefined:
function firstCharacter(text?: string): string {
if (text === undefined || text.length === 0) {
return "";
}
return text[0];
}The ? makes the parameter optional. An omitted optional parameter has the type string | undefined.
Common sources of `undefined`
Array lookups and methods often return undefined when no value exists:
const users = ["Ada", "Lin"];
const found = users.find(user => user === "Kai");
if (found !== undefined) {
console.log(found.toUpperCase());
}An if (found) check can also narrow a string, but it treats every empty string as false. Use an explicit undefined check when an empty string is valid data.
Optional properties behave similarly:
interface Settings {
theme?: "light" | "dark";
}
function themeLabel(settings: Settings): string {
return settings.theme ?? "light";
}The nullish coalescing operator, ??, uses the fallback only for null or undefined. Unlike ||, it preserves valid falsy values such as 0 and "".
Exercise
Exercise
Why does text.length produce an error when text has type string | null, and how should you fix it?
Show answer
The value may be null at runtime. Check whether text is null first, or return a fallback, before accessing length.