Beginner LevelJavaScript & TypeScript
What is the difference between type aliases and interfaces in TypeScript?
❓ Interview Prompt: Compare type alias vs interface regarding syntax, declaration merging, union types, and inheritance.
Both type and interface define shapes for objects and data, but have distinct capabilities:
Interface (interface Person {}):
•
Designed for object shapes and OOP contracts.
•
Supports Declaration Merging: multiple interfaces with the same name in the same scope merge automatically.
•
Extends via
extends keyword (interface Child extends Parent).Type Alias (type Person = {}):
•
Can alias primitives, unions, tuples, mapped types, and functions (
type ID = string | number;).•
Cannot be declaration-merged!
•
Combines via intersection operators (
type Child = Parent & { extra: boolean }).Code Implementation Example
typescript
// Interface declaration & extension
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
// Interface Declaration Merging
interface Window {
customProperty: string; // Merges into global Window interface!
}
// Type Alias supporting unions & primitives
type Status = 'pending' | 'success' | 'error';
type Point = { x: number; y: number };
type ID = string | number;💡Interface object extension & declaration merging vs type alias union definition.
🎯 Interview Key Takeaway
Use interface for object shapes and library public APIs (enabling declaration merging). Use type for unions and primitives.
#TypeScript#Interfaces#Type Aliases#Beginner
Back to all JavaScript & TypeScript Questions→