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
Section titled “typeof”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}Truthiness, and why || is a trap
Section titled “Truthiness, and why || is a trap”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 backUse ?? for defaults and !== undefined for checks. Use if (x) only when 0 and "" really
should count as missing.
Equality
Section titled “Equality”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
Section titled “instanceof”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}Type predicates
Section titled “Type predicates”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 | undefinedif (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.
Assertion functions
Section titled “Assertion functions”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 | undefinedassertDefined(url, "QUEUE_URL")url.length // string from here on
declare const port: number | stringassert(typeof port === "number", "port must be a number")port.toFixed(0) // number from here onControl flow
Section titled “Control flow”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.
Exercise
Section titled “Exercise”normalize has two type errors and two bugs that type-check. Fix all four: the tests cover
every form each setting can take.
typeoffor primitives (watch fornull),instanceoffor classes,infor object shapes,===for literals and discriminants.??and!== undefined, not||and truthiness, when0or""are valid.value is Tmoves a check into a function.asserts value is Tnarrows everything after it.
Further reading
Section titled “Further reading”- Handbook: Narrowing: every narrowing form in this lesson.