Sub topic 11
Handle null and undefined
Assume you know modern JavaScript, can run TypeScript with Node.js, and have already configured a project that compiles .ts files. This chapter focuses on null, undefined, and the compiler checks that prevent missing values from causing runtime errors.
Why missing values need types
JavaScript uses two common values for “no value”:
undefinedusually means a value was not provided or a property does not exist.nullusually means a value was deliberately set to nothing.
A JavaScript function may return either value without warning. TypeScript can make that possibility explicit.
With strictNullChecks enabled, a value of type string cannot be null or undefined. A function that might not find a user must declare that result:
interface User {
name: string;
age: number;
}
function findUser(users: User[], name: string): User | undefined {
return users.find((user) => user.name === name);
}The union type User | undefined means the result is either a User object or undefined.
Turn on strict null checking
If your project has "strict": false, enable only this check first:
{
"compilerOptions": {
"strict": false,
"strictNullChecks": true
}
}The compiler will now report unsafe uses. For example, this code fails because user might be undefined:
const user = findUser([{ name: "Ada", age: 36 }], "Grace");
// Error: user might be undefined
console.log(user.name.toUpperCase());Do not solve this by immediately adding a type assertion or suppressing the error. First prove that the value exists.
Narrow the type with a check
Type narrowing is the process of using a runtime check to reduce a wider type to a safer type. An if statement narrows user inside its block:
const user = findUser([{ name: "Ada", age: 36 }], "Grace");
if (user !== undefined) {
console.log(user.name.toUpperCase());
} else {
console.log("User not found");
}TypeScript understands that user is a User in the first branch. The else branch handles the missing case.
You can also use optional chaining when no action is needed for a missing value:
const displayName = user?.name.toUpperCase();The result is string | undefined. Optional chaining prevents an exception, but it does not create a name when no user exists.
Choose a fallback deliberately
Use the nullish coalescing operator, ??, when null or undefined should produce a default:
function getLabel(label: string | null | undefined): string {
return label ?? "Untitled";
}
console.log(getLabel(null)); // Untitled
console.log(getLabel("Report")); // Report?? differs from ||: it preserves valid falsy values such as "", 0, and false.
Follow the value through the program
Missing values often enter at boundaries such as API responses, form fields, and object properties. Keep the union type at that boundary, then narrow it before using the value.
Avoid the non-null assertion operator, written as !, unless you have a guaranteed invariant that the compiler cannot express. user!.name silences the warning but can still throw at runtime.
Exercise
What should findUser return when no matching user exists, and how should its caller use the result?
Show answer
It should return User | undefined. The caller should check whether the result is defined before reading its properties, or provide a deliberate fallback.