Union type (|) β OR relationship
βA value can be this OR that.β
Intersection type (&) β AND relationship
βA value must satisfy this AND that at the same time.β
Thatβs the essence β but letβs go deeper because behavior changes depending on how you use them.
A union type allows a variable to hold one of multiple possible types.
let id: string | number;
id = "abc123"; // β
okay
id = 101; // β
okay
id = true; // β error
π§ Meaning β id can either be a string OR a number, not both at once.
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase()); // β
safe
} else {
console.log(id.toFixed(2)); // β
safe
}
}
Here TypeScript forces you to narrow down the type before you use it.
Thatβs called Type Narrowing β a key TS feature.
interface User {
name: string;
}
interface Admin {
admin: boolean;
}
function getDetails(person: User | Admin) {
// You can only access common properties
// person.name β (not allowed β because Admin might not have 'name')
// person.admin β (not allowed β because User might not have 'admin')
// You must narrow type first:
if ("name" in person) {
console.log("User:", person.name);
} else {
console.log("Admin:", person.admin);
}
}
π§© Important point:
Union narrows access β you can only use common members until you check which one it actually is.