Explain it simply
Type narrowing, in plain language
When a variable could have several types, a runtime condition can prove which type it has in the current branch. TypeScript then narrows the broad type to that safer, more specific type.
The value is not converted into a new type. The runtime check gives the compiler more precise information about the value that already exists.
Problem → Why → Solution
Start with the problem
This function accepts either a string or a number. Calling toUpperCase() immediately causes a TypeScript error.
function printValue(value: string | number) {
console.log(value.toUpperCase())
}Why does TypeScript complain?
A string has toUpperCase(), but a number does not. Until the branch proves which type value has, calling that method is unsafe.
Core concept — prove, then use
Use a JavaScript runtime check such as typeof to choose a branch. Inside the matching branch, the compiler knows value is a string and safely exposes string methods.
- string | number
- typeof value === "string"
- string
A runtime check turns the broad type into a narrowed type for the current control-flow branch.
General pattern
if (typeof value === "string") {
// value is string here
}Inside the true branch, TypeScript narrows value to string.
The smallest useful example
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase())
} else {
console.log(value.toFixed(2))
}
}
printValue("hello")
printValue(12)Read the code step by step
- Line 1
value: string | numberThe function accepts either a string or a number.
- Line 2
typeof value === "string"This checks the value at runtime.
- Line 3
value.toUpperCase()In this branch TypeScript knows value is a string, so the method is safe.
- Lines 4–5
else / value.toFixed(2)If it is not a string, the only remaining possibility is number.
HELLO
12.00Each input type enters its matching branch.
- value: string | number
- typeof value === "string"?
Yes
string → toUpperCase()
No
number → toFixed()
Build up the narrowing patterns
1. Truthiness narrowing
if (value) removes falsy values such as null, undefined, an empty string, and zero. Be explicit when an empty string or zero is valid data.
function greet(name: string | null) {
if (!name) return "Hello, guest"
return `Hello, ${name}`
}2. Equality narrowing
After an === comparison succeeds, the compiler keeps the type that both values can share.
function compare(a: string | number, b: string | boolean) {
if (a === b) {
return a.toUpperCase() // both are string here
}
return "Different values"
}3. The in operator
For an object union, the in operator can narrow by checking whether a property exists.
type Admin = { name: string; permissions: string[] }
type Customer = { name: string; points: number }
function openDashboard(user: Admin | Customer) {
if ("permissions" in user) {
return `Admin tools: ${user.permissions.length}`
}
return `Reward points: ${user.points}`
}4. instanceof narrowing
Use instanceof for runtime values with a prototype chain, such as Date, Error, or class instances. Interfaces do not exist at runtime, so they cannot be used with instanceof.
function formatDate(value: Date | string) {
if (value instanceof Date) {
return value.toISOString()
}
return new Date(value).toISOString()
}5. Custom type guards
To reuse a complex object check, return a type predicate such as value is User. When the function returns true, the compiler narrows value to User.
type User = { id: string; name: string }
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false
const record = value as Record<string, unknown>
return typeof record.id === "string" &&
typeof record.name === "string"
}
function welcome(value: unknown) {
return isUser(value) ? `Welcome ${value.name}` : "Invalid user"
}6. Discriminated unions
Give every union member a shared literal field such as status. Checking that field narrows the entire branch precisely.
type ApiResult =
| { status: "success"; data: User[] }
| { status: "error"; message: string }
function renderResult(result: ApiResult) {
if (result.status === "success") {
return `Found ${result.data.length} users`
}
return `Error: ${result.message}`
}7. Exhaustive checking
Use never for exhaustive checking when every union member must be handled. Adding a new member then produces a compile-time error at the unhandled branch.
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${JSON.stringify(value)}`)
}
function render(result: ApiResult): string {
switch (result.status) {
case "success": return `${result.data.length} users`
case "error": return result.message
default: return assertNever(result)
}
}Production usage
Real project — validate API data at the boundary
Adding a TypeScript annotation to fetch().json() does not make runtime data valid. Accept external data as unknown, validate it at the boundary, and only then pass it into the application.
async function loadUser(): Promise<User> {
const response = await fetch("/api/user")
const data: unknown = await response.json()
if (!isUser(data)) {
throw new Error("Invalid user response")
}
return data // data is User here
}Valid data → returned as User
Invalid data → throws an ErrorThe type guard turns an untrusted boundary into a trusted application contract.
Common mistake — do not switch safety off with any
With any, the compiler stops checking properties and methods. unknown is safer for external data because it requires narrowing before use.
Unsafe
function print(value: any) {
value.toUpperCase() // compiles, but may crash
}Safer
function print(value: unknown) {
if (typeof value === "string") {
console.log(value.toUpperCase())
}
}Best practice
- Start external input as unknown and validate it at the boundary.
- Use one stable literal discriminant field for a union.
- Before using an as assertion, ask whether a runtime check or better contract can prove the type.
- Add a never exhaustive check when every union member must be handled.
Try it yourself
Complete double(). Multiply a number by two, or concatenate a string with itself. Use Run to test it.
function double(value: number | string) {
// Write your narrowing here
}
console.log(double(4))
console.log(double("Hi"))You'll know it worked when: 8 / HiHi
Mini challenge
getUserDisplayName()
Write a function that uses a type guard to distinguish User from Guest and returns the correct display name.
- Return name for User.
- Return Guest: <id> for Guest.
- Do not use any or a type assertion.
type User = { kind: "user"; name: string }
type Guest = { kind: "guest"; id: number }
function getUserDisplayName(person: User | Guest) {
// Your code
}Expected: A correct display name for both User and Guest.
Show hint
Check the kind field. This is a discriminated union.
Show solution
function getUserDisplayName(person: User | Guest) {
if (person.kind === "user") return person.name
return `Guest: ${person.id}`
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
Lesson summary
- Narrow a broad type with runtime checks.
- Choose between typeof, truthiness, equality, in, and instanceof.
- Validate untrusted data with a custom type guard.
- Use discriminated unions and never for exhaustive checking.
- Prefer unknown over any at unsafe boundaries.
TypeScript Handbook — Narrowing — TypeScript