TypeScript Custom Type Guards
Last Updated :
23 Jul, 2025
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 Tutorial TypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
TypeScript Basics
Introduction to TypeScriptTypeScript is a syntactic superset of JavaScript that adds optional static typing, making it easier to write and maintain large-scale applications.Allows developers to catch errors during development rather than at runtime, improving code reliability.Enhances code readability and maintainability wit
5 min read
Difference between TypeScript and JavaScriptEver wondered about the difference between JavaScript and TypeScript? If you're into web development, knowing these two languages is super important. They might seem alike, but they're actually pretty different and can affect how you code and build stuff online.In this article, we'll break down the
4 min read
How to install TypeScript ?TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
3 min read
Hello World in TypeScriptTypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows javascript syntactically but adds more features to it. It is a superset of javascript. The diagram below depicts the relationship:Typescript is purely object-oriented with features like
3 min read
How to execute TypeScript file using command line?TypeScript is a statically-typed superset of JavaScript that adds optional type annotations and compiles to plain JavaScript. It helps catch errors during development. To execute a TypeScript file from the command line, compile it using tsc filename.ts, then run the output JavaScript file with node.
2 min read
Variables in TypeScriptIn TypeScript, variables are used to store values that can be referenced and manipulated throughout your code. TypeScript offers three main ways to declare variables: let, const, and var. Each has different behavior when it comes to reassigning values and scoping, allowing us to write more reliable
6 min read
What are the different keywords to declare variables in TypeScript ?Typescript variable declarations are similar to Javascript. Each keyword has a specific scope. Let's learn about variable declarations in this article. In Typescript variables can be declared by using the following keywords:varlet constVar keyword: Declaring a variable using the var keyword.var vari
4 min read
Identifiers and Keywords in TypeScriptIn TypeScript, identifiers are names used for variables, classes, or methods and must follow specific naming rules. Keywords are reserved words with predefined meanings and cannot be used as identifiers. Comments, both single-line and multi-line, enhance code readability and are ignored during code
2 min read
TypeScript primitive types
Data types in TypeScriptIn 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.Prim
3 min read
TypeScript NumbersTypeScript Numbers refer to the numerical data type in TypeScript, encompassing integers and floating-point values. The Number class in TypeScript provides methods and properties for manipulating these values, allowing for precise arithmetic operations and formatting, enhancing JavaScript's native n
4 min read
TypeScript StringIn TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string. TypeSc
4 min read
Explain the concept of null and its uses in TypeScriptNull refers to a value that is either empty or a value that doesn't exist. It's on purpose that there's no value here. TypeScript does not make a variable null by default. By default unassigned variables or variables which are declared without being initialized are 'undefined'. To make a variable nu
3 min read
TypeScript Object types
What are TypeScript Interfaces?TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
4 min read
TypeScript classA TypeScript class is a blueprint for creating objects, encapsulating properties (data) and methods (behavior) to promote organization, reusability, and readability.Supports inheritance, allowing one class to extend another and reuse functionality.Provides access modifiers (public, private, protecte
4 min read
How enums works in TypeScript ?In this article, we will try to understand all the facts which are associated with enums in TypeScript. TypeScript enum: TypeScript enums allow us to define or declare a set of named constants i.e. a collection of related values which could either be in the form of a string or number or any other da
4 min read
TypeScript TuplesIn JavaScript, arrays consist of values of the same type, but sometimes we need to store a collection of values of different types in a single variable. TypeScript offers tuples for this purpose. Tuples are similar to structures in C programming and can be passed as parameters in function calls.Tupl
3 min read
TypeScript other types
What is any type, and when to use it in TypeScript ?Any is a data type in TypeScript. Any type is used when we deal with third-party programs and expect any variable but we don't know the exact type of variable. Any data type is used because it helps in opt-in and opt-out of type checking during compilation. In this article, we will see what is any
3 min read
How to Create an Object in TypeScript?TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
What is an unknown type and when to use it in TypeScript ?In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type. Â similar to any, we can assign any va
3 min read
Explain the purpose of never type in TypeScriptIn Typescript when we are certain that a particular situation will never happen, we use the never type. For example, suppose you construct a function that never returns or always throws an exception then we can use the never type on that function. Never is a new type in TypeScript that denotes value
3 min read
TypeScript combining types
TypeScript Assertions
TypeScript Functions
TypeScript interfaces and aliases
TypeScript classes
How to Extend an Interface from a class in TypeScript ?In this article, we will try to understand how we to extend an interface from a class in TypeScript with the help of certain coding examples. Let us first quickly understand how we can create a class as well as an interface in TypeScript using the following mentioned syntaxes: Syntax:Â This is the s
3 min read
How to Create an Object in TypeScript?TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.Creating Objects in TypescriptNow, let
4 min read
How to use getters/setters in TypeScript ?In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.Getters allow you to retrieve the value of a property with controlled logic.Setters enable controlled assignment to properties, often including validation or transformations.Java
5 min read
TypeScript InheritanceInheritance is a fundamental concept in object-oriented programming (OOP). It allows one class to inherit properties and methods from another class. The class that inherits is called the child class, and the class whose properties and methods are inherited is called the parent class. Inheritance ena
3 min read
When to use interfaces and when to use classes in TypeScript ?TypeScript supports object-oriented programming features like classes and interfaces etc. classes are the skeletons for the object. it encapsulates the data which is used in objects. Interfaces are just like types for classes in TypeScript. It is used for type checking. It only contains the declarat
4 min read
Generics Interface in typescript"A major part of software engineering is building components that not only have well-defined and consistent APIs but are also reusable. " This sentence is in the official documentation we would start with. There are languages that are strong in static typing & others that are weak in dynamic typ
5 min read
How to use property decorators in TypeScript ?Decorators are a way of wrapping an existing piece of code with desired values and functionality to create a new modified version of it. Currently, it is supported only for a class and its components as mentioned below: Class itselfClass MethodClass PropertyObject Accessor ( Getter And Setter ) Of C
4 min read