Menu
Coddy logo textTech

Type Guards: in & instanceof

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 69 of 73.

When working with union types, you often need to determine which specific type you're dealing with before you can safely access type-specific properties or methods. Type guards provide a safe way to narrow down types at runtime.

The in operator checks whether a property exists on an object. This is particularly useful when you have a union of object types with different properties:

type Dog = { name: string; breed: string };
type Cat = { name: string; meow: () => void };

function petSound(pet: Dog | Cat) {
  if ('breed' in pet) {
    // TypeScript knows pet is a Dog here
    console.log(`${pet.name} is a ${pet.breed}`);
  } else {
    // TypeScript knows pet is a Cat here
    pet.meow();
  }
}

The instanceof operator checks if an object was created by a specific constructor function or class. While we haven't covered classes yet, this operator is useful when working with built-in JavaScript objects or custom classes:

function processValue(value: string | Date) {
  if (value instanceof Date) {
    // TypeScript knows value is a Date
    console.log(value.getFullYear());
  } else {
    // TypeScript knows value is a string
    console.log(value.toUpperCase());
  }
}

Both operators help TypeScript's compiler understand which type you're working with, enabling safe access to type-specific properties and methods.

challenge icon

Challenge

Easy

Create a function that processes different types of media items using the in operator to distinguish between them.

Create two type aliases:

  • Movie with properties title (string) and director (string)
  • Song with properties title (string) and artist (string)

Create a function named getMediaInfo that:

  • Takes a parameter media of type Movie | Song
  • Uses the in operator to check if the director property exists
  • Returns "Movie: [title] directed by [director]" if it's a movie
  • Returns "Song: [title] by [artist]" if it's a song
  • Has an explicit return type of string

Create a second function named processValue that:

  • Takes a parameter value of type string | Date
  • Uses the instanceof operator to check if value is a Date
  • Returns the year as a number if it's a Date (using getFullYear())
  • Returns the string length as a number if it's a string
  • Has an explicit return type of number

Create test data:

  • movie1: { title: "Inception", director: "Christopher Nolan" }
  • song1: { title: "Bohemian Rhapsody", artist: "Queen" }
  • movie2: { title: "The Matrix", director: "The Wachowskis" }
  • song2: { title: "Imagine", artist: "John Lennon" }
  • testDate: new Date("2023-12-25")
  • testString: "TypeScript"

Print the following outputs:

  • Call getMediaInfo with movie1
  • Call getMediaInfo with song1
  • Call getMediaInfo with movie2
  • Call getMediaInfo with song2
  • Call processValue with testDate
  • Call processValue with testString

Try it yourself

// TODO: Write your code here

// Create type aliases for Movie and Song


// Create the getMediaInfo function


// Create the processValue function


// Create test data
const movie1 = { title: "Inception", director: "Christopher Nolan" };
const song1 = { title: "Bohemian Rhapsody", artist: "Queen" };
const movie2 = { title: "The Matrix", director: "The Wachowskis" };
const song2 = { title: "Imagine", artist: "John Lennon" };
const testDate = new Date("2023-12-25");
const testString = "TypeScript";

// Print the outputs
console.log(getMediaInfo(movie1));
console.log(getMediaInfo(song1));
console.log(getMediaInfo(movie2));
console.log(getMediaInfo(song2));
console.log(processValue(testDate));
console.log(processValue(testString));
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript