Menu

Narrowing with Type Guards

Lesson 2: Narrowing with Type Guards

What is narrowing?

Narrowing is how TypeScript refines a wide type to a more specific one based on checks in your code. It follows if, switch, return, and throw statements; this is called control flow analysis.

Check Narrows Example
typeof x === 'string' Primitives `string
Truthiness if (x) Removes null, undefined, '', 0 `string
Equality x === 'UPI' Literal values PaymentMethod → 'UPI'
'upiId' in x Objects by property Payment → UpiPayment
x instanceof Date Class instances `Date
Array.isArray(x) Arrays `string

Example

function formatDeliveryDate(value: Date | string | null): string {
  if (value === null) return 'Not scheduled';         // null removed
  if (value instanceof Date) return value.toLocaleDateString('en-IN');
  return new Date(value).toLocaleDateString('en-IN'); // value: string
}

type UpiPayment = { upiId: string };
type CardPayment = { last4: string };

function describePayment(p: UpiPayment | CardPayment): string {
  if ('upiId' in p) {
    return `UPI: ${p.upiId}`;   // p: UpiPayment
  }
  return `Card ending ${p.last4}`; // p: CardPayment
}

function normaliseTags(tags: string | string[]): string[] {
  return Array.isArray(tags) ? tags : [tags];
}

How it works

  • After an early return, TypeScript knows the removed case cannot reach the code below.
  • typeof null is 'object' in JavaScript, so check x !== null separately when narrowing objects.
  • Truthiness checks also remove 0 and ''. For numbers like stock counts, check x !== undefined instead of if (x).

Common mistakes

Mistake Effect Fix
if (stock) for a number that can be 0 Zero treated as missing if (stock !== undefined)
Assuming typeof x === 'object' excludes null Runtime crash Add x !== null
Using as instead of a check Wrong assumptions compile Narrow with a real runtime check

Key takeaways

  • Narrowing uses normal JavaScript checks, so it is safe at runtime too.
  • Choose the check that matches the type: typeof, in, instanceof, equality, or Array.isArray.

Try it: Write getDisplayPrice(price: number | string | undefined): string that handles all three cases, including a price of 0.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details