Sub topic 5
Narrowing: proving a value is present
This chapter assumes you know union types, can read a tsconfig.json, and have strictNullChecks enabled (usually through "strict": true). With that flag on, a value typed string | null cannot be used as a string until you show the compiler that it is not null. That showing is called narrowing.
What narrowing is
Narrowing is the compiler's process of refining a variable's type inside a region of code, based on checks it can see. TypeScript tracks this with control flow analysis. It reads your if statements, early returns, and operators, and at each line it works out which members of the union are still possible.
function lengthOf(s: string | null): number {
// here s is string | null
if (s === null) {
return 0;
}
// here s is string, because the null branch returned
return s.length;
}The declared type of s never changes. What changes is the narrowed type at each point in the code. After the if block returns, the only way to reach s.length is with s not null, so the compiler treats it as string.
Equality checks
Strict equality is the most direct form of narrowing. You can test for each missing value separately.
function show(s: string | null | undefined): string {
if (s === null) {
return "null";
}
if (s === undefined) {
return "undefined";
}
return s;
}Loose equality with null is the one place where == is idiomatic in TypeScript. The expression x == null is true for both null and undefined, and nothing else. The compiler understands this and removes both from the type.
function shout(s: string | null | undefined): string {
if (s == null) {
return "";
}
return s.toUpperCase();
}Many style guides ban == in general but allow this exact form. Check whether your linter has an exception for it (ESLint's eqeqeq rule has a "null": "ignore" option).
Truthiness checks
An if (x) test removes every falsy member of the type. For objects that means only null and undefined, so truthiness is safe and compact.
function nameLength(user: { name: string } | null): number {
if (!user) {
return 0;
}
return user.name.length;
}For primitives, truthiness removes more than you intend. Falsy values include 0, NaN, "", and false.
function describe(count: number | undefined): string {
if (!count) {
return "no count"; // also runs when count is 0
}
return `count is ${count}`;
}
console.log(describe(0)); // "no count", although 0 is a real valueThe compiler accepts this code because it is type-correct. The bug is in the logic, and narrowing cannot catch it. When the type is number | undefined, string | null, or boolean | undefined, prefer === undefined, === null, or == null so that 0, "", and false stay valid.
| Check | Removes from the type | Watch out for |
|---|---|---|
| `x === null` | `null` only | `undefined` remains |
| `x === undefined` | `undefined` only | `null` remains |
| `x == null` / `x != null` | both `null` and `undefined` | Needs a lint exception for `==` |
| `if (x)` / `!x` | all falsy values | Drops `0`, `""`, `false`, `NaN` too |
| `typeof x === "string"` | every type except `string` | Cannot distinguish `null` from an object |
| `x instanceof Date` | `null`, `undefined`, and non-`Date` types | Fails across realms (such as iframes) |
typeof and instanceof
typeof narrows to a primitive type. It works well when the union mixes several primitives with the missing value.
function format(value: string | number | null | undefined): string {
if (typeof value === "string") {
return value.trim();
}
if (typeof value === "number") {
return value.toFixed(2);
}
return "n/a"; // value is null | undefined here
}Be careful with typeof x === "object". In JavaScript, typeof null is "object". TypeScript models this correctly, so the narrowed type is object | null, and you still have to remove null.
function keysOf(value: object | string | null): string[] {
if (typeof value === "object" && value !== null) {
return Object.keys(value); // value is object
}
return [];
}instanceof narrows to a class. Because null and undefined are never instances of anything, one instanceof test removes them as well as other classes.
function formatDate(d: Date | string | null): string {
if (d instanceof Date) {
return d.toISOString();
}
return d ?? "no date";
}The in operator also narrows, but only between object types in a union. It does not remove null, and applying in to a possibly-null value is a type error under strict settings.
Combining conditions
Narrowing works through &&, ||, !, and the ternary operator. Short-circuiting is what makes && useful here. The right side only runs, and is only checked, when the left side passed.
function isNonEmpty(s: string | null): boolean {
return s !== null && s.length > 0;
}
function pick(a: string | null, b: string | null): string {
if (a === null || b === null) {
return "missing";
}
return a + b; // both are string here
}
const label = (s: string | null) => (s !== null ? s.toUpperCase() : "none");The || form in pick is a common guard-clause pattern. The if branch is entered when either value is missing. The code after it is only reachable when both are present, so both are narrowed.
Narrowing also follows throw, continue, and break, not only return.
function firstLengths(items: (string | null)[]): number[] {
const result: number[] = [];
for (const item of items) {
if (item === null) {
continue;
}
result.push(item.length); // item is string
}
return result;
}Narrowing through a saved condition
Since TypeScript 4.4, you can store a check in a const and test it later. The narrowing carries over when the checked variable is a const, a readonly property, or a parameter that is never reassigned.
function lengthOrZero(s: string | null): number {
const present = s !== null;
if (present) {
return s.length; // s is string
}
return 0;
}If s were declared with let and assigned somewhere in the function, this would stop working.
Where narrowing is lost
Narrowing is a static judgment about a particular point in the code. Three situations break it, and they cause most of the confusing "possibly null" errors.
Reassignment and callbacks
A callback may run later, after the variable has changed. If a let variable is assigned anywhere after the callback is created, the compiler discards the narrowing inside that callback.
let current: string | null = Math.random() > 0.5 ? "ada" : null;
if (current !== null) {
setTimeout(() => {
console.log(current.length); // Error: 'current' is possibly 'null'.
}, 100);
}
current = null;The fix is to copy the narrowed value into a const. A const cannot change, so its narrowing is safe in any callback.
let current: string | null = Math.random() > 0.5 ? "ada" : null;
if (current !== null) {
const stable = current; // type string, never reassigned
setTimeout(() => {
console.log(stable.length);
}, 100);
}Since TypeScript 5.4, closures created after the last assignment to a let variable or parameter keep their narrowing. Code that reassigns the variable later, as above, still loses it.
Property paths
Narrowing applies to references such as user.address, as long as nothing in between assigns to that path. The compiler does not assume that calling a function can change a property. This is a known unsound spot.
interface Box {
value: string | null;
}
function clear(b: Box): void {
b.value = null;
}
function risky(b: Box): number {
if (b.value !== null) {
clear(b);
return b.value.length; // compiles, but throws a TypeError at runtime
}
return 0;
}The safe habit is to read the property into a local const immediately after checking it, and use the local from then on.
function safer(b: Box): number {
const value = b.value;
if (value !== null) {
clear(b);
return value.length; // value is still the string we checked
}
return 0;
}Checks inside helper functions
A function that returns boolean tells the compiler nothing about its argument.
function isPresent(s: string | null): boolean {
return s !== null;
}
function bad(s: string | null): number {
if (isPresent(s)) {
return s.length; // Error: 's' is possibly 'null'.
}
return 0;
}The compiler cannot see inside isPresent when it checks bad. To pass the narrowing outward, the helper needs a type predicate. That feature is the subject of the type guards chapter later in this tutorial.
Reading the error messages
With strictNullChecks on, the two messages you will see most often are:
'x' is possibly 'null'.or'x' is possibly 'undefined'.The compiler found a use ofxwhere a member of the union is still possible. Look for the path that reaches this line without a check.Object is possibly 'null' or 'undefined'.appears in older compiler versions for the same situation.
When you see these, ask which of the three questions applies. Did I check at all? Did the check get lost on the way (callback, reassignment, function call)? Or did my check remove too little, such as !== null on a value that can also be undefined?
Exercise
This function compiles, but it returns the wrong text for a score of 0. Explain why, and rewrite the check so that 0 is reported as a score.
function report(score: number | undefined): string {
if (!score) {
return "no score";
}
return score: ${score};
}
Show answer
!score is true for every falsy value, and 0 is falsy, so a real score of 0 is treated as missing. Test for the missing value directly:
function report(score: number | undefined): string {
if (score === undefined) {
return "no score";
}
return score: ${score};
}
The type is number | undefined, so === undefined removes exactly the missing case and leaves number, including 0.
Exercise
Why does the compiler report an error on label.length in the callback below, and how can you fix it without using !?
let label: string | null = pickLabel();
if (label !== null) {
items.forEach(() => console.log(label.length));
}
label = null;
Show answer
label is a let variable that is assigned again after the callback is created, so the compiler cannot guarantee the callback sees a non-null value and discards the narrowing there. Copy the narrowed value into a const before the callback:
const stable = label;
items.forEach(() => console.log(stable.length));
Inside the if block label is string, so stable has type string and is never reassigned. Its type holds inside any callback.