Switch to infinite scroll (Full book)

Type narrowing

the case for type narrowing

Type narrowing is only needed when a type T is too broad, not precise enough for our needs. Instead, we want to work with values when they conform to U, a subset of T.

For example, when the value can be number or undefined, we want to filter out undefined values, so that we work with number values.

The main way to filter out unwanted values is through runtime checks combined with control flow, such as early returns or if statements. TypeScript can then assume the value is of type U, and so is the variable.

remove nullish values

We detect nullish and filter it out:

if (name == null) return
// nullish removed

if (name != null) {
    // nullish removed in this block
}

narrow down to a JS primitive

We identify the type with typeof:

if (typeof x !== "string") return
// guaranteed string

if (typeof x === "string") {
    // guaranteed string in this block
}

narrow to a Class instance

We use instanceof:

if (myDate instanceof Date) {
    // guaranteed Date
}
earlymorning logo

Type narrowing

the case for type narrowing

Type narrowing is only needed when a type T is too broad, not precise enough for our needs. Instead, we want to work with values when they conform to U, a subset of T.

For example, when the value can be number or undefined, we want to filter out undefined values, so that we work with number values.

The main way to filter out unwanted values is through runtime checks combined with control flow, such as early returns or if statements. TypeScript can then assume the value is of type U, and so is the variable.

remove nullish values

We detect nullish and filter it out:

if (name == null) return
// nullish removed

if (name != null) {
    // nullish removed in this block
}

narrow down to a JS primitive

We identify the type with typeof:

if (typeof x !== "string") return
// guaranteed string

if (typeof x === "string") {
    // guaranteed string in this block
}

narrow to a Class instance

We use instanceof:

if (myDate instanceof Date) {
    // guaranteed Date
}