0
0
Typescriptprogramming~20 mins

Why instanceof fails on interfaces in Typescript - See It in Action

Choose your learning style9 modes available
Why instanceof Fails on Interfaces
📖 Scenario: Imagine you are building a simple app where you want to check if an object follows a certain shape (interface) before using it.
🎯 Goal: You will learn why the instanceof operator does not work with interfaces in TypeScript and how to check object types safely.
📋 What You'll Learn
Create an interface called Person with properties name and age
Create a class called Employee that implements Person
Create an object of type Employee
Try to use instanceof Person and see why it fails
Use a type guard function to check if an object matches the Person interface
💡 Why This Matters
🌍 Real World
When working with TypeScript, you often want to check if objects have certain shapes before using them safely.
💼 Career
Understanding how to check types correctly helps prevent bugs and is important for writing reliable TypeScript code in professional projects.
Progress0 / 4 steps
1
Create the Person interface and Employee class
Create an interface called Person with properties name (string) and age (number). Then create a class called Employee that implements Person and has a constructor to set name and age.
Typescript
Need a hint?

Interfaces define a shape but do not exist at runtime. Classes create real objects you can check with instanceof.

2
Create an Employee object
Create a variable called emp and assign it a new Employee object with name as "Alice" and age as 30.
Typescript
Need a hint?

Use the new keyword to create an instance of the class.

3
Try using instanceof with the interface
Write an if statement that checks if emp instanceof Person and inside it, write console.log("emp is a Person"). Also add an else block with console.log("emp is NOT a Person").
Typescript
Need a hint?

Interfaces do not exist at runtime, so instanceof cannot check them.

4
Use a type guard function to check the interface
Create a function called isPerson that takes obj: any and returns obj is Person. Inside, check if obj has name and age properties with correct types. Then use if (isPerson(emp)) to print "emp is a Person", else print "emp is NOT a Person".
Typescript
Need a hint?

Type guard functions check properties manually because interfaces vanish after compiling.