0
0
Typescriptprogramming~15 mins

instanceof type guards in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using instanceof Type Guards in TypeScript
📖 Scenario: You are building a simple program that handles different types of animals. Each animal can make a sound, but the way to get the sound depends on the animal type. You want to safely check the type of each animal before calling its specific method.
🎯 Goal: Create a TypeScript program that uses instanceof type guards to identify animal types and call their specific sound methods.
📋 What You'll Learn
Create two classes: Dog and Cat with a method each to make a sound
Create an array called animals containing instances of Dog and Cat
Use a for loop with instanceof to check each animal's type
Print the sound each animal makes using the correct method
💡 Why This Matters
🌍 Real World
Type guards like <code>instanceof</code> help programs safely handle different object types, common in apps that work with many data models.
💼 Career
Understanding type guards is important for writing safe and clear TypeScript code, a skill valued in frontend and backend development jobs.
Progress0 / 4 steps
1
Create Dog and Cat classes
Create a class called Dog with a method bark() that returns the string "Woof!". Also create a class called Cat with a method meow() that returns the string "Meow!".
Typescript
Need a hint?

Use class keyword to create classes. Define methods inside classes that return the correct strings.

2
Create animals array with Dog and Cat instances
Create an array called animals that contains one instance of Dog and one instance of Cat.
Typescript
Need a hint?

Create the array with const animals = [new Dog(), new Cat()].

3
Use instanceof to check animal types
Write a for loop that iterates over animals using the variable animal. Inside the loop, use instanceof Dog to check if animal is a Dog and call animal.bark(). Use instanceof Cat to check if animal is a Cat and call animal.meow().
Typescript
Need a hint?

Use for (const animal of animals) and inside use if (animal instanceof Dog) and else if (animal instanceof Cat).

4
Print the sounds made by each animal
Run the program so it prints the sounds made by each animal in the animals array using the console.log statements inside the for loop.
Typescript
Need a hint?

Run the program and check the console output shows Woof! and Meow! on separate lines.