Concept Flow - Declaration merging for interfaces
Declare Interface A
Declare Interface A again
Merge properties of both
Use merged Interface A
When two interfaces share the same name, TypeScript merges their properties into one combined interface.
interface User {
name: string;
}
interface User {
age: number;
}
const user: User = { name: "Alice", age: 30 };| Step | Action | Interface 'User' Properties | Resulting Type |
|---|---|---|---|
| 1 | Declare interface User with 'name: string' | { name: string } | User has property 'name' |
| 2 | Declare interface User again with 'age: number' | { name: string, age: number } | User now has 'name' and 'age' |
| 3 | Create object 'user' of type User | { name: string, age: number } | Object must have both 'name' and 'age' |
| 4 | Assign { name: 'Alice', age: 30 } to 'user' | { name: string, age: number } | Valid assignment, no errors |
| Variable | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|
| User Interface Properties | { name: string } | { name: string, age: number } | { name: string, age: number } | { name: string, age: number } |
| user | undefined | undefined | uninitialized | { name: 'Alice', age: 30 } |
Declaration merging lets multiple interfaces with the same name combine their properties. Syntax: Declare interface multiple times with same name. Result: One interface with all properties merged. Objects must have all merged properties. Conflicting property types cause errors.
Person in TypeScript?interface declarations with the same name merge properties.interface Person declarations, which is correct. Options B and C mix types and interfaces or duplicate types, which do not merge. class Person { name: string } class Person { age: number } uses classes, which do not merge.interface Car { brand: string; }
interface Car { year: number; }
const myCar: Car = { brand: "Toyota", year: 2020 };
console.log(myCar.year);Car interfaces merge their properties, so Car has both brand and year.myCar correctly has both properties. Logging myCar.year outputs 2020.interface User { id: number; }
interface User { name: string; }
const user: User = { id: 1 };User interfaces merge, so User requires both id and name.user only has id, missing name, causing a type error.interface Product { id: number; }
interface Product { description?: string; price: number; }Product interface?Product interface requires id (number) and price (number), with optional description.id and price, valid. { id: 101, description: "Book" } misses price. { price: 29.99, description: "Book" } misses id. { id: 101 } misses price.Pass the test and this pattern moves unknown