JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext
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 guards
// 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
  }
}

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?