Thuta Learning
TypeScript
AdvancedProgrammingIntermediate

Type Narrowing and Type Guards

TypeScriptLesson 1625 min

What you'll walk away with

  • Safely narrow a union type with runtime conditions
  • Choose between typeof, in, instanceof, and custom type guards
  • Validate API data by starting from unknown
  • Write discriminated unions with exhaustive checking

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.

typescript
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.

A mental model to remember
  1. string | number
  2. typeof value === "string"
  3. string

A runtime check turns the broad type into a narrowed type for the current control-flow branch.

General pattern

typescript
if (typeof value === "string") {
  // value is string here
}

Inside the true branch, TypeScript narrows value to string.

The smallest useful example

typescript
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

  1. Line 1value: string | number

    The function accepts either a string or a number.

  2. Line 2typeof value === "string"

    This checks the value at runtime.

  3. Line 3value.toUpperCase()

    In this branch TypeScript knows value is a string, so the method is safe.

  4. Lines 4–5else / value.toFixed(2)

    If it is not a string, the only remaining possibility is number.

You should see
HELLO
12.00

Each input type enters its matching branch.

Execution flow
  1. value: string | number
  2. 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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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
}
You should see
Valid data   → returned as User
Invalid data → throws an Error

The 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

typescript
function print(value: any) {
  value.toUpperCase() // compiles, but may crash
}

Safer

typescript
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.

typescript
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.
typescript
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
typescript
function getUserDisplayName(person: User | Guest) {
  if (person.kind === "user") return person.name
  return `Guest: ${person.id}`
}

Quick quiz 1 / 3

What does typeof value === "string" do?

Quick quiz 2 / 3

Which type should untrusted API data start as?

Quick quiz 3 / 3

What is the main benefit of a never exhaustive check?

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

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Type Narrowing and Type Guards | Thuta Learning