ruk·si

🏷️ TypeScript
Narrowing

Updated at 2024-08-02 02:45

TypeScript uses type narrowing to narrow down the type of variable within a block of code. This is useful when you have something that could be of multiple types.

  • Narrowing: a value cannot be one or more possible types
  • Expanding: a value can be two or more possible types
let person = Math.random() > 0.5 ? undefined : "Matthew";
// person is `undefined | string`

// typeof narrowing
if (typeof person === "string") {
    person.toUpperCase();
}

// direct check narrowing
if (person == "Matthew") {
    person.toUpperCase();
}

// truth narrowing
person && person.toUpperCase();
person?.toUpperCase();

// property narrowing
if ("toUpperCase" in person) {
    person.toUpperCase();
}

Discriminated unions are a common pattern in TypeScript where you have a union of types that have a common property that identifies the type in the variable.

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

interface Circle {
    kind: "circle";
    radius: number;
}

type Shape = Square | Rectangle | Circle;

function area(s: Shape) {
    switch (s.kind) {
        case "square":
            return s.size * s.size;
        case "rectangle":
            return s.width * s.height;
        case "circle":
            return Math.PI * s.radius ** 2;
    }
}

Sources

  • Learning TypeScript by Josh Goldberg