Type Guards in Typescript
Type Guards in Typescript

Type Guards in Typescript

In this blog, we In this blog, we will know Why are Type Guards necessary in TypeScript? and we will discuss Various Types of Type Guards and Their Use Cases.


Type guard is a typescript technique, which is used to determine information about type of a variable dynamically. This is where type guards come into play. Type guards are techniques used in TypeScript to determine the type of a variable within a conditional block, allowing you to narrow down the type and use the appropriate methods and properties.


Various Types of Type Guards and Their Use Cases

  • typeof
  • instanceof
  • in


The typeof type guard


The typeof type guard is used to determine the primitive type of a variable. It can check for the following types:

  • boolean
  • string
  • bigint
  • symbol
  • undefined
  • function
  • number

Code example:

const add = (param1: number | string, param2: number | string): number | string => {
    if (typeof param1 === 'number' && typeof param2 === 'number') {
        return param1 + param2;
    } else {
        return param1.toString() + param2.toString();
    }
};        

In this example, the typeof guard checks whether both param1 and param2 are numbers. If they are, it adds them; otherwise, it concatenates them as strings.


The instanceof type guard


The instanceof type guard checks whether an object is an instance of a particular class. This is useful when working with class hierarchies and inheritance.

Code example:

class Person {
    constructor(public name: string, public id: number) {}
    
    getName() {
        console.log(this.name);
    }
}

class Teacher extends Person {
    constructor(name: string, id: number, public salary: number) {
        super(name, id);
    }
    
    getSalaries() {
        console.log(this.salary);
    }
}

const student = new Person('Habib', 7);
const teacher = new Teacher('Utsho', 44, 5000);

const showTeacherSalaries = (param: Person) => {
    if (param instanceof Teacher) {
        param.getSalaries();
    } else {
        console.log('Invalid teacher');
    }
};

showTeacherSalaries(teacher); // Outputs: 5000
        

In this example, instanceof checks if param is an instance of Teacher. If true, it calls the getSalaries method; otherwise, it prints 'Invalid teacher'.


The in type guard


The in type guard checks whether an object has a specific property. It returns a boolean value indicating the presence of the property.

Code example:

interface Adult {
    isMarried: boolean;
}

interface Teenage {
    isDoll: string;
}

let person: Adult | Teenage = {
    isMarried: true
};

const getIdentifier = (person: Adult | Teenage) => {
    if ('isMarried' in person) {
        console.log('Adult');
    } else if ('isDoll' in person) {
        console.log('Not adult.');
    } else {
        console.log('Not a recognized person type');
    }
};

getIdentifier(person); // Outputs: Adult        

In this example, the in guard checks if person has the isMarried property. If true, it identifies the person as an adult; if it has the isDoll property, it identifies them as a teenager.


Conclusion


Type guards in TypeScript are essential for ensuring type safety during runtime. By using typeof, instanceof, and in type guards, you can effectively narrow down types and utilize the correct properties and methods, leading to more robust and error-free code.

要查看或添加评论,请登录

Ahashan Habib Utsho的更多文章

社区洞察

其他会员也浏览了