Nullable Values and Safe Access
Safe Narrowing
Guard checks narrow nullable values before later code depends on them.
narrowing guard
A guard check removes `null` or `undefined` from a union for the code that follows.
Safe Narrowing
narrowing.ts
Replay: real traced execution (multi-file project)
function parseLength(text: string | undefined): string {
if (text === undefined) {
return "missing";
}
const length: number = text.length;
return `length=${length}`;
}
const rawInput: string | undefined = "hello";
const result: string = parseLength(rawInput);
console.log(result);
function parseLength(text: string | undefined): string {
if (text === undefined) {
return "missing";
}
const length: number = text.length;
return `length=${length}`;
}
const rawInput: string | undefined = undefined;
const result: string = parseLength(rawInput);
console.log(result);
function parseLength(text: string | undefined): string {
if (text === undefined) {
return "missing";
}
const length: number = text.length;
return `length=${length}`;
}
const rawInput: string | undefined = "TypeScript";
const result: string = parseLength(rawInput);
console.log(result);
rawInput ← hello
6 return `length=${length}`;7}89const rawInput→ hello: string | undefined = "hello"; //@rawInput=undefined, "TypeScript"10const result: string = parseLength(rawInputhello);length ← 5, text.length ← 5
1function parseLength(texthello: string | undefined): string {2 if (text === undefined) {3 return "missing";4 }5 const length→ 5: number = text.length→ 5;6 return `length=${length5}`;7}result ← length=5
9const rawInput: string | undefined = "hello"; //@rawInput=undefined, "TypeScript"10const result→ length=5: string = parseLength(rawInputhello);1112console.log(resultlength=5);outputlength=5
rawInput ← undefined
6 return `length=${length}`;7}89const rawInput→ undefined: string | undefined = undefined;10const result: string = parseLength(rawInputundefined);function parseLength(text: string | undefined): string
1function parseLength(textundefined: string | undefined): string {2 if (text === undefined) {if (text === undefined)
1function parseLength(text: string | undefined): string {2 if (textundefined === undefined) {3 return "missing";4 }result ← missing
9const rawInput: string | undefined = undefined;10const result→ missing: string = parseLength(rawInputundefined);1112console.log(resultmissing);outputmissing
rawInput ← TypeScript
6 return `length=${length}`;7}89const rawInput→ TypeScript: string | undefined = "TypeScript";10const result: string = parseLength(rawInputTypeScript);length ← 10, text.length ← 10
1function parseLength(textTypeScript: string | undefined): string {2 if (text === undefined) {3 return "missing";4 }5 const length→ 10: number = text.length→ 10;6 return `length=${length10}`;7}result ← length=10
9const rawInput: string | undefined = "TypeScript";10const result→ length=10: string = parseLength(rawInputTypeScript);1112console.log(resultlength=10);outputlength=10