Open In App

TypeScript Custom Type Guards

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript boasts a powerful type system, which helps the developers catch errors at compile time and write more resilient code. Sometimes you would need to work with complex types or dynamically typed data where the type information might not be readily available. In situations like these, TypeScript offers something called type guards that help to narrow down the type of a variable within a particular block of code. Type guards can be customized to perform checks on specific types on behalf of the user.

What Are Type Guards?

These are functions or expressions that let TypeScript understand what type of variables are in a block. For instance, when working with union types, it is important to understand that a variable may hold several different types of values. This helps maintain safety while checking for errors during runtime.

Prerequisites

These are the approaches for TypeScript Custom Type Guards:

Creating Custom Type Guards

A custom type guard returns a boolean and accepts an argument. A return type arg Type is the most important part of such a custom type guard where Type represents the kind you are testing. For example, if this function returns true then TypeScript will consider arg as being of Type inside that block.

Syntax

function isTypeName(arg: any): arg is TypeName {
// custom logic to determine if arg is of TypeName
return /* boolean expression */;
}

Custom Type Guard for Discriminated Union

In this case, a type guard isCircle is used to check if the shape in question is a Circle by examining its kind property. This way getArea function can access properties specific to particular shape types as it uses this type guard.

Example: This example shows the creation of custom type guard for discriminated union.

JavaScript
interface Circle {
    kind: 'circle';
    radius: number;
}

interface Rectangle {
    kind: 'rectangle';
    width: number;
    height: number;
}

type Shape = Circle | Rectangle;
function isCircle(shape: Shape): shape is Circle {
    return shape.kind === 'circle';
}

function getArea(shape: Shape): number {
    if (isCircle(shape)) {
        // TypeScript knows shape is a Circle here
        return Math.PI * shape.radius ** 2;
    } else {
        // TypeScript knows shape is a Rectangle here
        return shape.width * shape.height;
    }
}

// Example usage
const myCircle: Shape = { kind: 'circle', radius: 10 };
const myRectangle: Shape = { kind: 'rectangle', width: 20, height: 10 };

console.log(getArea(myCircle));     // Output: 314.1592653589793
console.log(getArea(myRectangle));  // Output: 200

Output:

314.1592653589793
200

Custom Type Guard for Unknown Types

At times, you could work with unknown data types like when they are imported from other sources (user input or APIs). Type guards of our own be of assistance in making sure that the data follows expected formats.

Example: In this example, isUser function checks if an object has the structure of a User by checking the types of its properties. Thus, after confirming the type, one can safely operate on name and age properties using type guard.

JavaScript
interface User {
    name: string;
    age: number;
}

function isUser(obj: any): obj is User {
    return typeof obj.name === 'string' && typeof obj.age === 'number';
}

// Example usage
const data: any = { name: 'Pankaj', age: 20 };

if (isUser(data)) {
    // TypeScript knows data is a User here
    console.log(`User: ${data.name}, Age: ${data.age}`);
} else {
    console.log('Data is not a valid User.');
}

Output:

User: Pankaj, Age: 20

Using Type Guards in Array Filtering

You may also find custom type guards helpful when working with arrays containing many types so that you can remove elements from a given type. For instance, the function isPlant determines whether an organism happens to be a Plant depending upon the it hasFlowers parameter, however, in this instance, filter method applies this type guard only for creating array of plants alone.

Example: This example shows the use of type guards for array filtering.

JavaScript
type Animal = { species: string };
type Plant = { species: string; hasFlowers: boolean };

type Organism = Animal | Plant;

function isPlant(organism: Organism): organism is Plant {
	return 'hasFlowers' in organism;
}

const organisms: Organism[] = [
	{ species: 'Cat' },
	{ species: 'Rose', hasFlowers: true },
	{ species: 'Oak', hasFlowers: false },
];

const plants = organisms.filter(isPlant);
console.log(plants);

Output:

[
{ species: 'Rose', hasFlowers: true },
{ species: 'Oak', hasFlowers: false }
]

Custom Type Guards with instanceof

In TypeScript, the instanceof operator is applicable for verifying if an object belongs to a particular class. This is particularly true when dealing with objects of a class type and you need to refine the type to a specific class. By leveraging on instanceof you can write your own customized type guard that allows TypeScript to understand the correct type in a block of code.

Example: This is an instance of the Dog class checking example which uses instanceof operator in order to tell difference between Dog and Cat types.

JavaScript
class Dog {
    bark() {
        console.log("Woof!");
    }
}

class Cat {
    meow() {
        console.log("Meow!");
    }
}

function isDog(animal: Dog | Cat): animal is Dog {
    return animal instanceof Dog;
}

function makeSound(animal: Dog | Cat) {
    if (isDog(animal)) {
        animal.bark(); // TypeScript knows it's a Dog here
    } else {
        animal.meow(); // TypeScript knows it's a Cat here
    }
}

const dog = new Dog();
makeSound(dog); // Output: Woof!

Output:

Woof!

Custom Type Guards with typeof

When working with primitive types such as string, number, boolean and symbol, typeof operator works as a kind of type guard. It enables narrowing down the type of a variable in situations where it includes these primitives within union types.

Example: This example illustrates how typeof may be used as a type guard separating number from string allowing safe operations based on variable type.

JavaScript
function isNumber(value: string | number): value is number {
    return typeof value === 'number';
}

function doubleValue(value: string | number) {
    if (isNumber(value)) {
        return value * 2; // TypeScript knows it's a number here
    }
    return value + value; // TypeScript knows it's a string here
}

console.log(doubleValue(10)); // Output: 20
console.log(doubleValue("Hi")); // Output: HiHi

Output:

20
HiHi

Custom Type Guards for Complex Types

For more complicated types, such as objects with multiple properties, particular conditions may have to be checked in order to identify their type. before you take any actions, custom type guards can help you verify that the shape and property types are exactly as you expect them to be.

Example: Type guard created here to identify a Car vehicle by searching for some properties that would enable accurate type inference for complex objects.

JavaScript
interface Car {
    make: string;
    model: string;
    year: number;
}

interface Bicycle {
    brand: string;
    gears: number;
}

function isCar(vehicle: Car | Bicycle): vehicle is Car {
    return (vehicle as Car).make !== undefined && (vehicle as Car).model !== undefined;
}

function getVehicleInfo(vehicle: Car | Bicycle) {
    if (isCar(vehicle)) {
        console.log(`Car: ${vehicle.make} ${vehicle.model}, Year: ${vehicle.year}`);
    } else {
        console.log(`Bicycle: ${vehicle.brand}, Gears: ${vehicle.gears}`);
    }
}

const car: Car = { make: "Toyota", model: "Corolla", year: 2022 };
getVehicleInfo(car); // Output: Car: Toyota Corolla, Year: 2022

Output:

Car: Toyota Corolla, Year: 2022

Conclusion

Custom type guards in TypeScript are highly effective at guaranteeing type safety when dealing with complicated or variable data types. When you define your own type guards, the information about variable types will be more precise and that way you can produce more accurate checks as well as reduce runtime errors. Custom type guards enable you to write safer and more maintainable code when working with discriminated unions, unknown data structures, or mixed-type arrays.


Next Article

Similar Reads