Skip to content

Narrowing

Relay can also read relay.json. People write it by hand, so "port": 3000 and "port": "3000" both show up, "tls" is sometimes true and sometimes an object with file paths, and "retries": 0 must mean never retry, not use the default. Each setting is a union, and the code has to find out which member it has before using it. That’s narrowing: a check the compiler understands shrinks the type inside the branch.

typeof distinguishes primitives: "string", "number", "boolean", "bigint", "symbol", "undefined", "function" and "object".

function readPort(port: number | string): number {
if (typeof port === "number") return port // number
return Number(port.trim()) // string
}

if (x) removes undefined and null, but it also removes 0, "", NaN and false, which are often real values:

declare const retries: number | null | undefined
const wrong = retries || 3 // 0 becomes 3: "never retry" turned into "retry 3 times"
const right = retries ?? 3 // only null and undefined fall back

Use ?? for defaults and !== undefined for checks. Use if (x) only when 0 and "" really should count as missing.

Comparing with === or !== narrows both sides. It’s also how literal unions and discriminants narrow:

function readTls(tls: boolean | { cert: string; key: string } | undefined) {
if (tls === undefined || tls === false) return "off"
if (tls === true) return "self-signed"
return tls // { cert: string; key: string }
}

"key" in value narrows a union of object types to the members that have that key:

type Auth = { token: string } | { user: string; password: string }
function header(auth: Auth): string {
if ("token" in auth) return `Bearer ${auth.token}`
return `Basic ${btoa(`${auth.user}:${auth.password}`)}`
}

instanceof narrows to a class. It’s the usual check for errors:

function message(err: Error | string): string {
if (err instanceof Error) return err.message
return err
}

When a check is too involved to write inline, move it into a function that returns value is T. The compiler then narrows wherever the function is called:

interface TlsFiles {
cert: string
key: string
}
function isTlsFiles(value: boolean | TlsFiles | undefined): value is TlsFiles {
return typeof value === "object"
}
declare const tls: boolean | TlsFiles | undefined
if (isTlsFiles(tls)) {
tls.cert // TlsFiles
}

The compiler trusts the predicate without checking it. If the body is wrong, the narrowing is wrong, so keep predicates small.

asserts value is T narrows everything after the call, and the function throws when the check fails. It suits a check that should stop the program:

function assert(condition: boolean, message: string): asserts condition {
if (!condition) throw new Error(message)
}
function assertDefined(value: string | undefined, name: string): asserts value is string {
if (value === undefined) throw new Error(`${name} is required`)
}
declare const url: string | undefined
assertDefined(url, "QUEUE_URL")
url.length // string from here on
declare const port: number | string
assert(typeof port === "number", "port must be a number")
port.toFixed(0) // number from here on

Narrowing follows return, throw, else and early exits, not only if blocks. After if (x === undefined) return, the rest of the function sees x without undefined. Reassigning a variable resets what’s known about it.

normalize has two type errors and two bugs that type-check. Fix all four: the tests cover every form each setting can take.

  • typeof for primitives (watch for null), instanceof for classes, in for object shapes, === for literals and discriminants.
  • ?? and !== undefined, not || and truthiness, when 0 or "" are valid.
  • value is T moves a check into a function. asserts value is T narrows everything after it.