Interface Declaration Merging Combines Fields
Merge three interface declarations into one type, add optional fields from each block, and inspect the combined key union.
Code
interface User {
id: number;
}
interface User {
name: string;
}
interface User {
email?: string;
role?: 'admin' | 'member';
}
// Declaration merging combines every interface block into one type.
const user: User = { id: 7, name: 'Ada' };
console.log(user.id, user.name, user.email ?? 'no email');
const admin: User = { id: 8, name: 'Grace', role: 'admin' };
console.log(admin.role);
type UserKeys = keyof User;
const keys: UserKeys[] = ['id', 'name', 'email', 'role'];
console.log(keys.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
7 Ada no email
admin
id,name,email,roleHow it works
The top-level object literal pins id, name as plain values — no derivation, no imports behind them.
What to watch for
- Nothing external is pulled in — the language’s built-in APIs carry everything.
Key statements
type UserKeys = keyof User;
Interactive Tools for This Topic
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free.
Report a problem with this exampleOpens a pre-filled issue on GitHub.