Sub topic 9
Possibly undefined: narrowing the value
Assume you know JavaScript arrays and functions, TypeScript annotations, and union types. This chapter focuses on strictNullChecks, a compiler option that treats undefined as a separate type.
Why the compiler complains
Some operations cannot promise that a value exists. For example, Array.find returns the first matching item, or undefined when no item matches.
const names: string[] = ["Ada", "Alan"];
const first = names.find((name) => name.startsWith("A"));
// Error: 'first' is possibly 'undefined'
// console.log(first.length);The type of first is string | undefined. The vertical bar means a union: the value can have either type. TypeScript rejects first.length because undefined has no length property.
This is a safety check. The array might be empty, or the search might fail after the program changes.
Narrowing with a condition
Narrowing means checking a value so TypeScript can use a more specific type in a particular part of the code.
const names: string[] = ["Ada", "Alan"];
const first = names.find((name) => name.startsWith("Z"));
if (first !== undefined) {
console.log(first.length);
} else {
console.log("no matching name");
}Inside the if block, the condition proves that first is not undefined. TypeScript narrows its type from string | undefined to string. Inside the else block, the value is known to be undefined.
A truthiness check often works too:
if (first) {
console.log(first.length);
}For strings, this also excludes the empty string. Use an explicit !== undefined check when an empty string is a valid result and must be handled separately.
Other ways to handle the case
Choose a strategy based on the program's rules.
- Use a condition when no result is a normal possibility.
- Use a default with
??when a fallback is correct. - Throw an error when the absence means the program cannot continue.
- Return
undefinedfrom your own function when callers should decide what to do. - Use optional chaining when you want to safely skip an operation.
const names: string[] = ["Ada", "Alan"];
const first = names.find((name) => name.startsWith("Z"));
const lengthOrZero = first?.length ?? 0;
console.log(lengthOrZero);
function requiredName(values: string[]): string {
const result = values.find((value) => value.length > 0);
if (result === undefined) {
throw new Error("A non-empty name is required");
}
return result;
}Optional chaining, written as ?., returns undefined instead of accessing a property on a missing value. The nullish coalescing operator, written as ??, supplies a fallback only for null or undefined.
Exercise
Exercise
Why does TypeScript allow first.length inside an if (first !== undefined) block but reject it before the check?
Show answer
The condition narrows first from string | undefined to string inside that block. Before the check, the value might still be undefined.