Guard checks narrow nullable values before later code depends on them.

Safe Narrowing

narrowing.ts
function parseLength(text: string | undefined): string {
    if (text === undefined) {
        return "missing";
    }
    const length: number = text.length;
    return `length=${length}`;
}

const rawInput: string | 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 = ;
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 = ;
const result: string = parseLength(rawInput);

console.log(result);
narrowing guard A guard check removes `null` or `undefined` from a union for the code that follows.