Union & Intersection Types
Combine types with `|` for "one of these" and with `&` for "all of these, merged."
What is it?
Some values can take more than one shape. A lookup function might accept an id (a number) or a slug (a string). No single basic type describes that.
A union type, written A | B, is a value that is one of several types. string | number means "a string or a number." Before doing something that only works for one of them, you must check which one you have (this is narrowing, covered in a later topic).
An intersection type, written A & B, goes the other way: the value must satisfy all the shapes at once. If A has name and B has age, then A & B is one object with both name and age.
Explain like I'm 10
A union is a form field that accepts "a phone number or an email": either one. An intersection is a job application that needs a resume AND a cover letter: every piece, in one submission.
Examples
A union type for flexible input
function lookup(idOrSlug: number | string): void {
console.log(`Looking up: ${idOrSlug}`);
}
lookup(42); // OK — it's a number
lookup("my-post"); // OK — it's a string
lookup(true);
// Error: Argument of type 'boolean' is not assignable
// to parameter of type 'string | number'.idOrSlug may be a number or a string, nothing else. Any other value is rejected.
An intersection type combining two shapes
interface HasName {
name: string;
}
interface HasAge {
age: number;
}
type Person = HasName & HasAge;
const p: Person = { name: "Tariq", age: 41 }; // must have both
const invalid: Person = { name: "Tariq" };
// Error: Property 'age' is missing in type
// '{ name: string; }' but required in type 'HasAge'.Person is the intersection of HasName and HasAge, so a Person needs every property from both.
How it works
For a union A | B, the compiler only allows operations that are safe for both A and B. Anything specific to one needs narrowing first (checking which one you have at runtime).
For an intersection A & B, the compiler merges the members of both and requires an object to have all of them. So it combines the requirements, even though it's called an intersection.
Why does it exist?
Real data often varies in shape. An API response might be a success or an error object; a function might accept a couple of input forms. Unions describe that precisely, instead of falling back to any and losing all checking.
Intersections let you build a bigger shape from smaller reusable pieces instead of repeating properties across similar interfaces.
When to use it
Use a union when a value can really be more than one type: a result that can succeed or fail, a parameter that accepts a few related shapes, or data from an unpredictable external source.
Use an intersection to combine smaller, independently useful shapes into one, especially if those shapes are reused on their own.
When not to use it
Don't pile more than a handful of types into one union. Code handling every case gets hard to read, and it may mean the values should share a common structure (see discriminated unions).
Don't intersect incompatible types (like string & number, which gives the unusable never type). Intersections only make sense between compatible object shapes.
Common mistakes
Accessing a property that exists on only one branch of a union before narrowing.
Confusing
|and&. A union (|) means "could be either"; an intersection (&) means "must be both, combined."Intersecting types that share a property name with conflicting types (like
stringandnumber), which silently turns that property intonever.
Practice exercises
- Easy:
Write a type alias
Idasstring | numberand a functionprintId(id: Id): voidthat logs it. - Medium:
Define interfaces
Timestamped(createdAt: Date) andNamed(name: string). Combine them into an intersection typeNamedEventand create a valid object of that type. - Hard:
Write a function that accepts
string | string[]and always returns astring[]: wrap a single string in an array, or return the array as-is.
Interview questions
What can you safely do with a value typed `string | number` before narrowing it?
Only operations valid for both branches. Anything specific to one type is refused until you check which one you have.
What does `A & B` require of a value, in terms of properties?
Every member of both A and B at once. An intersection combines requirements instead of offering a choice.
Why does intersecting two incompatible primitive types, like `string & number`, produce the `never` type?
No value can be both a string and a number, so the set of valid values is empty. TypeScript calls that empty set never.
Given `function f(x: string | number) { x.toUpperCase(); }`, why does this fail to compile even though `x` might genuinely be a string at runtime?
TypeScript checks the type, not the actual value. x could be a number, which has no toUpperCase, so the call isn't safe for every case the union allows.
If `HasName` and `HasAge` both declare `id: string` with the same type, what happens when you intersect them?
They merge into one id: string requirement. A conflict only happens when the same property has incompatible types.
What happens to a property that two intersected types declare with conflicting, incompatible types (e.g. `string` in one, `number` in the other)?
It becomes never, since no value can be both types. The resulting type is effectively impossible to construct.
In what sense does an intersection type `A & B` combine "requirements" rather than combine "possibilities"?
A union widens what's acceptable (either type qualifies). An intersection narrows it to values that meet every requirement of both types at once.
How would you type a function that accepts either a single `string` or an array of strings?
As string | string[]. You then narrow it (for example with Array.isArray) before treating it as one or the other.
Why does TypeScript reject calling a method that exists on only one branch of a union, without an explicit runtime check first?
The compiler can't prove which branch you have there, so it only allows operations valid for every branch until a check narrows the type.
What's the practical difference between typing a parameter as `string | number` versus typing it as `any`?
string | number still requires one of those two types and narrowing before type-specific use. any turns off checking, allowing any value and any operation.
Is `{ name: "Tariq" }` assignable to `type Person = HasName & HasAge`?
No. The intersection needs every property from both, so an object missing age fails, even though it satisfies HasName.
Why are intersection types useful for building up a type from smaller, reusable pieces?
You define small interfaces once and combine them with & where needed, instead of repeating the same properties in several similar interfaces.
Why should you avoid piling more than a handful of types into a single union?
Handling every branch gets hard to read past a few cases, and it often means the values share a structure better expressed as a discriminated union.
What's a cleaner alternative to a large union of many related object shapes?
A discriminated union: give each shape a shared "tag" property with a distinct literal value, so checking that one property narrows cleanly to the right branch.
Can a union mix primitive and object types, like `string | { id: number }`? What's the implication for using it?
Yes, a union can contain any kinds of types. But each branch still needs its own narrowing check (like typeof for the string) before you use anything specific to it.
Why does `lookup(42)` succeed and `lookup(true)` fail for a parameter typed `number | string`?
42 matches one of the union's types. boolean isn't in number | string, so it matches neither branch.
If `A` and `B` each declare a method with the same name but different, incompatible parameter types, what tends to happen when you intersect them?
TypeScript intersects the two function types. In practice that usually accepts only arguments valid for both signatures at once, often too strict to call usefully.
Why is a union type's *value space* the combination of its branches' values, while an intersection type's *value space* is narrower than either type alone?
A union accepts a value matching any branch, so each branch added grows the set. An intersection requires a value to meet every type's requirements at once, so adding types only shrinks the set (or leaves it the same).