TypeScript Custom Type Guards
Last Updated :
21 Aug, 2024
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.
Similar Reads
TypeScript Assertions Type
TypeScript Assertions Type, also known as Type Assertion, is a feature that lets developers manually override the inferred or expected type of a value, providing more control over type checking in situations where TypeScript's automatic type inference may not be sufficient. Syntax let variableName:
2 min read
TypeScript any Type
In TypeScript, any type is a dynamic type that can represent values of any data type. It allows for flexible typing but sacrifices type safety, as it lacks compile-time type checking, making it less recommended in strongly typed TypeScript code. It allows developers to specify types for variables, f
4 min read
TypeScript Conditional Types
In TypeScript, conditional types enable developers to create types that depend on a condition, allowing for more dynamic and flexible type definitions. They follow the syntax T extends U ? X : Y, meaning if type T is assignable to type U, the type resolves to X; otherwise, it resolves to Y.Condition
4 min read
Recursive Type Guards In TypeScript
In TypeScript type guards help determine the type of a variable at runtime, they are especially useful when dealing with complex types like unions, discriminated unions or even recursive structures and a recursive type guard is a type guard function that can handle complex nested types, including th
6 min read
TypeScript Object Tuple Types
TypeScript provides various features to enhance type safety and developer productivity. One of these features includes Object Tuple Types. This feature ensures that an object follows a consistent shape in our code which results in a reduction in runtime errors and improves code quality. What are Obj
5 min read
TypeScript Interfaces Type
TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach. Syntax:interface InterfaceName { property1: type1; property2?: type2; readonly property3: type3; // ... method1(): returnType1; method2(): returnType2; // ...}Parameters:in
2 min read
TypeScript Object Types
TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters. Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
3 min read
How to use Type Guards in TypeScript ?
Here are the methods to use type guards in TypeScript: 1. Using typeof Type GuardsThe typeof operator checks the type of a variable, primarily for primitive types like string, number, boolean, etc. [GFGTABS] JavaScript function processValue(value: string | number) { if (typeof value === 'string
3 min read
Data types in TypeScript
In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
3 min read
TypeScript Object Type Index Signatures
In this article, we are going to learn about Object Type Index Signatures in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, index signatures allow you to define object types with dynamic keys, where the keys can be of a spe
2 min read