interface vs type alias: when do you use each?
Both describe the shape of objects and are interchangeable for most props and models.
interface
- Only for object shapes (and function or class contracts).
- Declaration merging: two
interface Windowdeclarations combine, which is how you add fields to globals or library types. extendsgives clearer error messages and is slightly faster for the compiler on large hierarchies.
type
- Can name any type: unions (
'sm' | 'md' | 'lg'), tuples, primitives, mapped and conditional types. - Combines with intersections (
A & B). - Cannot be reopened or merged.
A practical rule
Use type for unions and computed types, and either for object shapes, picking one convention for the team. Many React codebases use type Props = {...}; library authors often prefer interface so users can augment it.
Example
ts
type Size = 'sm' | 'md' | 'lg';
type Point = [x: number, y: number];
interface ButtonProps {
size?: Size;
onClick: () => void;
}
interface IconButtonProps extends ButtonProps {
icon: string;
}
type Loading = { status: 'loading' };
type Loaded = { status: 'loaded'; data: string[] };
type State = Loading | Loaded; // only a type alias can express a union
declare global {
interface Window { analytics?: { track(e: string): void } } // declaration merging
}Follow-up questions interviewers ask
Try answering each one before you open it.
What does `as const` do?
It makes a literal as narrow and readonly as possible: ['GET', 'POST'] as const becomes readonly ['GET', 'POST'] instead of string[]. It is handy for deriving unions from data: type Method = typeof methods[number]. The satisfies operator checks a value against a type while keeping its narrow literal type.