Narrowing
How the checker follows control flow, and exhaustiveness with never.
typeof
Chapter 2 left a union you could not use. A typeof check is the fix — inside the branch,
the type is just string:
function format(v: string | number) {
if (typeof v === "string") {
return v.toUpperCase()
}
return v.toFixed(2)
}
console.log(format("ada"), format(3.14159))The return after the if gets number without a second check. The checker eliminated
string by following the control flow:
function format(v: string | number) {
return v.toUpperCase()
}Truthiness
A plain if (n) narrows too, and that is the problem. This compiles clean:
function label(n: number | undefined) {
if (n) {
return n.toFixed(0)
}
return "none"
}
console.log(label(5))
console.log(label(0))
console.log(label(undefined))Test for the thing you actually mean:
function label(n: number | undefined) {
if (n !== undefined) {
return n.toFixed(0)
}
return "none"
}
console.log(label(5))
console.log(label(0))
console.log(label(undefined))Equality
=== against a literal narrows a literal union to one member:
function go(role: "admin" | "guest") {
if (role === "admin") {
return "all access"
}
return role.toUpperCase()
}
console.log(go("admin"), go("guest"))For null and undefined together, loose == is the deliberate exception — it matches
both and nothing else:
function f(v: string | null | undefined) {
if (v == null) {
return "empty"
}
return v.toUpperCase()
}
console.log(f(null))
console.log(f(undefined))
console.log(f("ada"))The in operator
When the members share no primitive type, narrow by which property exists:
type Dog = { bark: () => string }
type Fish = { swim: () => string }
function move(pet: Dog | Fish) {
if ("bark" in pet) {
return pet.bark()
}
return pet.swim()
}
console.log(move({ bark: () => "woof" }))Without the check, neither method is available — only what both types have:
type Dog = { bark: () => string }
type Fish = { swim: () => string }
function move(pet: Dog | Fish) {
return pet.bark()
}instanceof
For anything built with a class — Date, Error, your own types:
function describe(v: Date | string) {
if (v instanceof Date) {
return v.toISOString()
}
return v.toUpperCase()
}
console.log(describe(new Date(0)))
console.log(describe("ada"))Inside that branch the type really is Date, so a string method is an error:
function describe(v: Date | string) {
if (v instanceof Date) {
return v.toUpperCase()
}
return v
}Discriminated unions
This is the pattern to reach for. Give every member the same field with a different
literal type, and a switch on that field narrows each branch:
type Circle = { kind: "circle"; radius: number }
type Square = { kind: "square"; side: number }
type Shape = Circle | Square
function area(s: Shape) {
switch (s.kind) {
case "circle":
return Math.PI * s.radius ** 2
case "square":
return s.side ** 2
}
}
console.log(area({ kind: "square", side: 3 }))radius is reachable only in the "circle" branch. Reading the wrong field is caught:
type Circle = { kind: "circle"; radius: number }
type Square = { kind: "square"; side: number }
function area(s: Circle | Square) {
if (s.kind === "circle") {
return s.side
}
return 0
}Exhaustiveness with never
Nothing is assignable to never, which turns a forgotten case into a compile error.
Assign the value to a never where every case should already have returned:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
function area(s: Shape) {
switch (s.kind) {
case "circle":
return Math.PI * s.radius ** 2
case "square":
return s.side ** 2
default: {
const never: never = s
return never
}
}
}
console.log(area({ kind: "square", side: 3 }))Now add a third shape and forget its case. The default becomes reachable, so s is no
longer never:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; height: number }
function area(s: Shape) {
switch (s.kind) {
case "circle":
return Math.PI * s.radius ** 2
case "square":
return s.side ** 2
default: {
const never: never = s
return never
}
}
}An annotated return type catches it too, but says much less:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; height: number }
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.radius ** 2
case "square":
return s.side ** 2
}
}Type predicates
Move a check into a function and the checker follows it, as long as the function is a single expression:
function isString(v: unknown) {
return typeof v === "string"
}
const v: unknown = "ada"
if (isString(v)) {
console.log(v.toUpperCase())
}Add a statement and the inference stops. The helper now returns a plain boolean, which
narrows nothing:
function isString(v: unknown) {
const t = typeof v
if (t === "number") return false
return t === "string"
}
const v: unknown = "ada"
if (isString(v)) {
console.log(v.toUpperCase())
}The fix is to say what the true result proves, with v is string:
function isUser(v: unknown): v is { handle: string } {
return typeof v === "object" && v !== null && "handle" in v
}
const data: unknown = JSON.parse('{"handle":"ada"}')
if (isUser(data)) {
console.log(data.handle)
}The same inference is why this works without any annotation — filter gives string[],
not (string | null)[]:
const xs: (string | null)[] = ["a", null]
const ys = xs.filter((v) => v !== null)
const check: string[] = ys
console.log(check)Assertion functions
When the failure case should throw rather than branch, asserts v is User narrows
everything after the call:
type User = { handle: string }
function assertUser(v: unknown): asserts v is User {
if (typeof v !== "object" || v === null || !("handle" in v)) {
throw new Error("not a user")
}
}
const data: unknown = JSON.parse('{"wrong":1}')
try {
assertUser(data)
console.log(data.handle)
} catch (err) {
console.log((err as Error).message)
}There is no if. The call either throws or data is a User from that line on.
type User = { handle: string }
const assertUser = (v: unknown): asserts v is User => {
if (typeof v !== "object") throw new Error("no")
}
const data: unknown = {}
assertUser(data)
console.log(data.handle)Where narrowing is lost
A property read does not stay narrowed inside a callback, because the object could change in between:
type Box = { value: string | null }
function f(b: Box) {
if (b.value !== null) {
;[1].forEach(() => {
console.log(b.value.toUpperCase())
})
}
}Copy it into a const first. A const cannot change, so the narrowing holds:
type Box = { value: string | null }
function f(b: Box) {
const value = b.value
if (value !== null) {
;[1].forEach(() => {
console.log(value.toUpperCase())
})
}
}
f({ value: "ada" })A let captured by a callback loses it for the same reason:
let v: string | null = "ada"
if (v !== null) {
setTimeout(() => {
console.log(v.toUpperCase())
}, 0)
}There is one case the checker misses. A function that reassigns the variable is not tracked, so this compiles clean and crashes:
let v: string | null = "ada"
function reset() {
v = null
}
if (v !== null) {
reset()
try {
console.log(v.toUpperCase())
} catch (err) {
console.log((err as Error).message)
}
}