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
.