Sub topic 5
Equality checks and null/undefined handling
This chapter assumes you know basic TypeScript syntax, union types such as string | number, and JavaScript if statements. It also assumes you have seen the idea that TypeScript narrows a union inside a branch. Here you will see how equality checks do that narrowing, with a focus on null and undefined.
Why equality narrows
When you compare a value with ===, !==, ==, or !=, TypeScript learns something about the value in each branch. In the branch where the comparison is true, the value can only be of types that could actually be equal to the other operand. In the other branch, the compiler removes the types it has ruled out.
The compiler does this by reading your control flow. It does not run your code. It only reasons about the shape of the checks.
function compare(x: string | number, y: string | boolean): void {
if (x === y) {
// x and y can only be equal if both are strings
console.log(x.toUpperCase());
console.log(y.toUpperCase());
} else {
console.log(x); // string | number
console.log(y); // string | boolean
}
}In the true branch, the only type that x and y share is string. TypeScript narrows both variables to string. In the else branch, equality tells you nothing, because the values could be two different strings. Both variables keep their full types.
Comparing with a literal
Comparing with a literal value narrows a variable to that literal type, and removes it from the other branch when the variable's type is a union of literals.
type Status = "idle" | "loading" | "done";
function label(status: Status): string {
if (status === "idle") {
return "Waiting";
}
// status is now "loading" | "done"
if (status !== "loading") {
// status is "done"
return "Finished";
}
return "Working";
}This is the same mechanism that powers discriminated unions, which a later chapter covers. Checking shape.kind === "circle" is an equality check on a property.
The null and undefined problem
With strictNullChecks turned on (part of strict), null and undefined are separate types. A value that might be missing has a union type such as string | null or string | undefined. You must remove the missing cases before you use the value.
function length(text: string | null): number {
if (text === null) {
return 0;
}
return text.length; // text is string
}The check text === null removes null from the type in the code that follows, because the true branch returns.
The same works with !==:
function length2(text: string | null): number {
if (text !== null) {
return text.length;
}
return 0;
}Strict equality is exact
=== compares to exactly one value. If your type is string | null | undefined, then === null removes only null. The value may still be undefined.
function broken(name: string | null | undefined): number {
if (name === null) {
return 0;
}
// name is string | undefined here
return name.length; // error: 'name' is possibly 'undefined'
}The compiler reports the error because it tracked the type correctly. You have a real bug: a caller can pass undefined.
Loose equality with `== null`
JavaScript's loose equality has one special rule that is useful here: value == null is true for both null and undefined, and for nothing else. Also, value != null is true for everything except those two. TypeScript understands this rule and narrows accordingly.
function greet(name: string | null | undefined): string {
if (name == null) {
return "Hello, stranger";
}
return `Hello, ${name.toUpperCase()}`;
}After the early return, name is string. One comparison removed both missing cases.
You can get the same result with two strict checks:
function greetStrict(name: string | null | undefined): string {
if (name === null || name === undefined) {
return "Hello, stranger";
}
return `Hello, ${name.toUpperCase()}`;
}Which form should you use?
| Form | Removes | Notes | Column | Column |
|---|---|---|---|---|
| `x === null` | `null` only | Leaves `undefined` in the type | ||
| `x === undefined` | `undefined` only | Leaves `null` in the type | ||
| `x == null` | `null` and `undefined` | Short; many lint configs flag `==` | ||
| `x === null \ | \ | x === undefined` | `null` and `undefined` | Longer; passes strict-equality lint rules |
Many teams enable the ESLint rule eqeqeq, which bans ==. It usually has an option, "null": "ignore", that allows == null as the one exception. Follow your project's convention. Both forms narrow the same way.
Why not use a truthiness check?
You might write if (!name) instead. That also removes null and undefined, but it removes more: the empty string "", 0, NaN, and false are all falsy too. For a string | null value, if (!name) treats an empty string like a missing value. That may be wrong for your program.
function describeCount(count: number | undefined): string {
if (!count) {
return "no count"; // also runs when count is 0
}
return `count is ${count}`;
}
function describeCountFixed(count: number | undefined): string {
if (count === undefined) {
return "no count";
}
return `count is ${count}`; // 0 is handled as a real number
}Use an equality check when 0 or "" is a legal value that should be kept.
Narrowing with `!==` on optional properties
Optional properties have the type T | undefined. The same checks apply.
type Options = { retries?: number };
function retryCount(options: Options): number {
if (options.retries !== undefined) {
return options.retries; // number
}
return 3;
}TypeScript narrows the property access options.retries itself, not only simple variables. This works as long as nothing between the check and the use could change the property. The final chapter of this tutorial covers the cases where it cannot be trusted.
Switch statements are equality checks
A switch compares the subject with each case using strict equality, so it narrows in the same way.
function handle(value: string | number | null): string {
switch (value) {
case null:
return "nothing";
case 0:
return "zero"; // value is 0
default:
return String(value); // value is string | number
}
}Inside case null, value is null. Inside case 0, it is the literal 0. In the default branch, null has been removed.
Alternatives to explicit checks
Sometimes you do not need a branch at all. Two operators handle missing values in a single expression.
function displayName(name: string | null | undefined): string {
return name ?? "anonymous";
}
function firstLetter(name: string | null | undefined): string | undefined {
return name?.charAt(0);
}??(nullish coalescing) returns the right side only when the left side isnullorundefined. Unlike||, it keeps""and0.?.(optional chaining) stops and yieldsundefinedif the value before it isnullorundefined.
Optional chaining also narrows in conditions. After if (user?.address !== undefined), TypeScript knows user is not null or undefined, because the chain could only produce a defined value if user existed.
type User = { address?: { city: string } } | null;
function city(user: User): string {
if (user?.address !== undefined) {
return user.address.city; // user is non-null here
}
return "unknown";
}Common errors
- Checking only one of
nullandundefined. The compiler error mentions the one you forgot. Use== nullor check both. - Using truthiness when
0,"", orfalseare valid. Switch to=== undefinedor=== null. - Comparing against a variable that is not a literal type. If
yhas typestring, thenx === ynarrowsxtostring, but it cannot narrowxto one specific value. Only literal and unit types such asnull,undefined,"idle", ortruenarrow to a single value. - Using the non-null assertion
!to silence an error. Writingname!.lengthremoves the error but adds no runtime check. Ifnameis missing, the program throws. Prefer a real check. - Forgetting that
typeof nullis"object". Atypeof x === "object"check keepsnullin the type. Combine it with an equality check, as intypeof x === "object" && x !== null.
How the flow looks
Summary of rules
===and!==narrow by removing the types that cannot equal the other value.== nulland!= nullhandlenullandundefinedtogether.- Equality is the right tool when falsy values such as
0and""are valid data. switchnarrows through strict equality in eachcase.??and?.can replace a branch when you only need a default or a safe access.
Exercise
The function below fails to compile with "'id' is possibly 'undefined'". Rewrite the check so it compiles, and keep 0 as a valid id.
function describe(id: number | null | undefined): string {
if (id === null) {
return "missing";
}
return id ${id.toFixed(0)};
}
Show answer
The check id === null removes only null, so undefined remains. Use if (id == null) or if (id === null || id === undefined). Do not use if (!id), because that would treat 0 as missing. For example: if (id == null) { return "missing"; } return id ${id.toFixed(0)};
Exercise
Given function f(x: string | number, y: string | boolean), what is the type of x inside if (x === y) { ... }, and why?
Show answer
string. The two values can be strictly equal only if they have a type in common, and the only common type of string | number and string | boolean is string.