Concept Flow - How intersection combines types
Type A
Intersection Type
Combined properties of A and B
Intersection takes two types and creates a new type that has all properties from both types.
type A = { name: string };
type B = { age: number };
type C = A & B;
const person: C = { name: "Alice", age: 30 };| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define type A | A = { name: string } | Type A created with property name:string |
| 2 | Define type B | B = { age: number } | Type B created with property age:number |
| 3 | Create intersection type C = A & B | C has properties of A and B combined | C = { name: string, age: number } |
| 4 | Declare variable person of type C | person must have name:string and age:number | person = { name: "Alice", age: 30 } |
| 5 | Access person.name | person.name is string | "Alice" |
| 6 | Access person.age | person.age is number | 30 |
| 7 | Try to assign person missing age | Error: age missing | TypeScript error |
| 8 | Try to assign person missing name | Error: name missing | TypeScript error |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| person | undefined | undefined | undefined | { name: "Alice", age: 30 } | { name: "Alice", age: 30 } |
Intersection types combine multiple types into one. Syntax: type C = A & B; Result: C has all properties from A and B. Variables of type C must have all combined properties. Missing any property causes a TypeScript error.
A & B represent?A & B means the type must satisfy both A and B simultaneously.TypeA and TypeB in TypeScript?& to combine types.& correctly. type Combined = TypeA | TypeB; uses union |, C and D use invalid operators for types.person?
type Name = { name: string };
type Age = { age: number };
const person: Name & Age = { name: "Alice", age: 30 };Name & Age means the type must have both name and age properties.name: "Alice" and age: 30, matching both types.type A = { x: number };
type B = { y: string };
const obj: A & B = { x: 10 };A & B requires properties from both A and B, so both x and y must be present.x: 10 but is missing y, so it does not satisfy the intersection type.type Contact = { email: string; phone: string | null };type Personal = { name: string; phone: string };info in this code?const info: Contact & Personal = {
name: "Bob",
email: "bob@example.com",
phone: "123-456"
};phone property is string | null in Contact and string in Personal. Intersection requires a type assignable to both, which is string.name, email, and phone as a string, matching the intersection type.name: string, email: string, and phone: string (the stricter type).Pass the test and this pattern moves unknown