How to Check the Type of an Object in Typescript ?
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below.
Table of Content
- Using the typeof Operator
- Using the instanceof Operator
- Using Type Guards
Using the typeof Operator
This operator returns a string indicating the type of the operand. We can operate this with the objects to check their type in TypeScript.
Syntax:
typeof variableName
Example: The below example demonstrates how to use the typeof operator to determine the type of a variable.
interface myInterface {
name: string,
est: number
}
let x: myInterface = {
name: "GFG",
est: 2009
};
console.log(typeof x);
Output:
object
Using the instanceof Operator
This operator checks whether an object is an instance of a particular class or constructor. We can operate it by defining the testing object name before it and the class name after it.
Syntax:
objectName instanceof ClassName
Example: The below example illustrates the usage of the instanceof operator to check if an object is an instance of a class.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
let person = new Person("John");
console.log(person instanceof Person);
Output:
true
Using Type Guards
Type guards are functions that return a boolean indicating whether an object is of a specific type.
Syntax:
function isType(obj: any): obj is TypeName {
// Type checking logic
}
Example: The below example demonstrates the implementation of a type guard function to check if an object satisfies a specific interface.
interface Animal {
name: string;
}
function isAnimal(obj: any):
obj is Animal {
return obj &&
typeof obj.name === 'string';
}
let animal = {
name: "Dog",
sound: "Bark"
};
if (isAnimal(animal)) {
console.log(animal.name);
}
Output:
Dog
Contact Us