Type Predicates in TypeScript

Introduction

Functions in which the return value is a boolean and is used in order to determine what data type is a variable is known as a Type Predicate.

Structure

function is<Type>(variable: datatype): variable is Type {
    //Logic and return boolean
}

Example

type User = {
    id: number
    name: string
};

type Employee = User & {
    position: string
}


const employees: (User | Employee)[] = [
    {id: 1, name: "Abdullah"},
    {id: 2, name: "Ahmad", position: "Engineer"},   
    {id: 3, name: "Aisha"},    
    {id: 4, name: "Fatima", position: "Project Manager"},
];

employees.forEach((individual) => {
	if(isEmployee(individual)) {
  	console.log(`name: ${individual.name}, position: ${individual.position}`);
  } else {
  	console.log(`name: ${individual.name}`);
  }
});

function isEmployee (individual: User | Employee): individual is Employee{
	return "position" in individual
};

In the example above we have created two types: User and Employee. Employee is an intersection of User. We then have an array of objects called employees which is composed of objects of types User and Employee. Finally, we create the Type Predicate function called isEmployee to check whether the object that is passed in at each iteration is of type Employee or User.

This blog post was originally published on my blog Communicode, where I write about different tech topics.

TypeScript
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.