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.

Javascript
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

Similar Reads

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....

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....

Using Type Guards

Type guards are functions that return a boolean indicating whether an object is of a specific type....