How to use Type Guards In Typescript
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
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