Sub topic 1
TypeScript null and undefined with strictNullChecks
Prerequisites
Assume you know basic TypeScript types, interfaces, union types, and tsconfig.json. You should also know that JavaScript has both null and undefined.
null and undefined: two ways to say “no value”
JavaScript uses undefined when a value is missing by default. For example, a missing object property produces undefined. A function that does not return a value also returns undefined.
null is an explicit value that usually means “deliberately empty.” APIs often use it to represent an absent result.
TypeScript keeps these values distinct when strictNullChecks is enabled. A string does not automatically include either one.
What strictNullChecks changes
Enable the option in tsconfig.json:
{
"compilerOptions": {
"strict": true
}
}The strict setting includes strictNullChecks. With this option, TypeScript reports unsafe assignments and use:
let name: string = "Ada";
// name = null; // Error: Type 'null' is not assignable to type 'string'.
let maybeName: string | null = null;
maybeName = "Ada";Without strict checking, null and undefined can flow into ordinary types more easily. That can cause runtime errors when code calls a method on a missing value.
Writing nullable types with unions
A union type allows a value to have one of several types. Write string | null when a value is either a string or explicitly empty. Write string | undefined when it may be missing. If both forms are possible, write string | null | undefined.
Code must check the value before using it:
function shout(value: string | null | undefined): string {
if (value == null) {
return "";
}
return value.toUpperCase();
}The == null check is intentional here. It matches both null and undefined, and TypeScript narrows value to string after the early return.
Optional properties and parameters
An optional property or parameter uses ?. An optional property behaves like a property whose value may be undefined:
interface User {
name: string;
address?: {
city?: string;
};
}
function greeting(name?: string): string {
return `Hello, ${name ?? "guest"}`;
}Use optional members when callers may omit a value. Use | null when the value is present as a field or argument but can deliberately contain null.
Exercise
What type should describe a value that may be a number or missing, but never null?
Show answer
number | undefined.