JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext

Learn the concept

Type Guards & Narrowing

typescript
mid
type-guards

What are type guards in TypeScript and how do you create custom ones?

type-guards
narrowing
type-predicates
typeof
instanceof
Quick Answer

Type guards are runtime checks that narrow types within conditional blocks. Built-in guards include typeof, instanceof, and in operators. Custom type guards are functions returning a type predicate (param is Type) to narrow types based on custom logic.

Detailed Explanation

Built-in Type Guards:

  • typeof: For primitives (string, number, boolean, etc.)
  • instanceof: For class instances
  • in: For checking property existence
  • Equality narrowing: === null, !== undefined

Custom Type Guards:

  • Function returning param is Type
  • Called "type predicates"
  • Runtime check that narrows type in condition
  • Useful for discriminating unions, API responses

Why Use Type Guards:

  • Safely access type-specific properties
  • Avoid type assertions (as Type)
  • Make code self-documenting
  • Enable exhaustive checking

Code Examples

Built-in type guardsTypeScript
// typeof guard for primitives
function process(value: string | number) {
  if (typeof value === 'string') {
    console.log(value.toUpperCase()); // value is string
  } else {
    console.log(value.toFixed(2));    // value is number
  }
}

// instanceof guard for classes
class Dog { bark() { return 'woof'; } }
class Cat { meow() { return 'meow'; } }

function speak(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    console.log(animal.bark()); // animal is Dog
  } else {
    console.log(animal.meow()); // animal is Cat
  }
}

// 'in' operator guard
interface Fish { swim: () => void; }
interface Bird { fly: () => void; }

function move(animal: Fish | Bird) {
  if ('swim' in animal) {
    animal.swim(); // animal is Fish
  } else {
    animal.fly();  // animal is Bird
  }
}

Real-World Applications

Use Cases

API Response Validation

Using type guards to validate and narrow untyped API responses before business logic

User Permission Checking

Type guards that narrow user types based on role, enabling type-safe access to role-specific properties

Form Data Processing

Using assertion functions to validate form submissions match expected shapes before processing

Mini Projects

Schema Validator with Type Guards

intermediate

Build a runtime validator that returns type-guarded results using custom predicates

Type-Safe JSON Parser

advanced

Implement a JSON parser that uses assertion functions to guarantee parsed data matches expected TypeScript types

Industry Examples

Zod

Uses type guards internally for parse/safeParse that narrow unknown input to validated types

io-ts

Uses type guard predicates for runtime type validation with TypeScript type narrowing

Resources

TypeScript - Narrowing

docs

Related Questions

What are union and intersection types in TypeScript?

junior
unions

What are generics in TypeScript and how do you use them?

mid
generics
Previous
What are generics in TypeScript and how do you use them?
Next
What are TypeScript's built-in utility types and when do you use them?
PrevNext