💻 Tech
Intersection and union types allow flexible use of types, especially if the properties change. An intersection type combines different types and properties into one type, while a union type represents a type that can be one of multiple types.
If a function is using a union type and you want to ensure you’re working with a particular type, you can use type guards. Type guards ensure type safety by telling the compiler if an object is of a particular type.
interface EmployeeBasic {
name: string;
age: number;
}
const emp: EmployeeBasic = {
name: "Buzz",
age: 40,
};
// Intersection type
// GovernmentEmployee combines the properties of EmployeeBasic and another GovtBranchNo property
type GovernmentEmployee = EmployeeBasic & { GovtBranchNo: string };
const govtEmp: GovernmentEmployee = {
...emp,
GovtBranchNo: "123",
};
// PrivateEmployee combines the properties of EmployeeBasic and another CompanyNo property
type PrivateEmployee = EmployeeBasic & { CompanyNo: string };
const privEmp: PrivateEmployee = {
...emp,
CompanyNo: "456",
};
// Union type
// Employee can be of type GovernmentEmployee or PrivateEmployee
type Employee = GovernmentEmployee | PrivateEmployee;
function processEmployee(emp: Employee) {
if (isGovernmentEmployee(emp)) {
console.log(emp.GovtBranchNo);
} else if (isPrivateEmployee(emp)) {
console.log(emp.CompanyNo);
}
}
function isGovernmentEmployee(emp: Employee): emp is GovernmentEmployee {
return (emp as GovernmentEmployee).GovtBranchNo !== undefined;
}
function isPrivateEmployee(emp: Employee): emp is PrivateEmployee {
return (emp as PrivateEmployee).CompanyNo !== undefined;
}
processEmployee(govtEmp); // 123
processEmployee(privEmp); // 456