Sub topic 15
Choosing between interface and type alias
This chapter assumes you can already write both constructs: object shapes with interface and type, optional and readonly properties, unions, intersections, generics, and implements. Here the focus is on deciding which one to use, and on the cases where the choice changes behavior.
Start with what is the same
For plain object shapes, interface and type are interchangeable. Both are checked structurally, so a value matches if it has the required properties, whatever the declaration was called. Both support optional and readonly properties, method and call signatures, index signatures, and type parameters. A class can implement either one, as long as the alias names an object type.
interface PointI {
x: number;
y: number;
}
type PointT = {
x: number;
y: number;
};
const a: PointI = { x: 1, y: 2 };
const b: PointT = a; // fine: same shape
console.log(a, b);Because the overlap is so large, most real decisions come down to the places where the two differ.
What only one of them can do
| Capability | `interface` | `type` | Column |
|---|---|---|---|
| Object shape | Yes | Yes | |
| Union (`A \ | B`) | No | Yes |
| Literal types such as `"idle"` | No | Yes | |
| Tuples | Only by awkward workaround | Yes | |
| Mapped types (`[K in keyof T]`) | No | Yes | |
| Conditional types | No | Yes | |
| Alias for a primitive (`type ID = string`) | No | Yes | |
| Declaration merging | Yes | No (duplicate identifier error) | |
| `extends` another type | Yes | No, but `&` gives a similar result | |
| Implicit index-signature compatibility | No | Yes, for object literal types |
Anything that is not an object shape pushes you toward type. An interface cannot name a union, a tuple, or a mapped type, so those cases need no further deliberation.
type Status = "idle" | "loading" | "done";
type Pair<A, B> = [A, B];
type Flags<T> = { [K in keyof T]: boolean };Extending: `extends` versus `&`
Both approaches build a larger shape from a smaller one. They differ when the two parts conflict.
interface Base {
id: number;
}
// Error: Interface 'Bad' incorrectly extends interface 'Base'.
// Types of property 'id' are incompatible.
// interface Bad extends Base {
// id: string;
// }
type Mixed = { id: number } & { id: string };
// Mixed compiles, but its id has type number & string, which is never.An interface that extends another reports an incompatible property at the declaration, which is where the mistake is. An intersection accepts the conflict and gives you an unusable property type. You then find the problem later, when you try to create a value of that type. For this reason, prefer extends when you are building a hierarchy of object shapes.
Two other points about extension:
- An interface can extend an object type alias, and an alias can intersect an interface, so you can mix them freely.
- An interface cannot extend a union type, because a union is not a single object shape. If you try, the compiler reports that an interface can only extend an object type or intersection of object types with statically known members.
Declaration merging: a feature and a hazard
Two interfaces with the same name in the same scope merge into one. This is the only way to add members to a type you do not own, such as Window or a library's interface.
export {};
declare global {
interface Window {
appVersion: string;
}
}
window.appVersion = "1.4.0";The same mechanism can bite you inside your own code. If two files both declare interface Config in the same scope, TypeScript silently combines them instead of reporting a clash. A typo in a name can also create a new, mostly empty interface instead of an error. A type alias gives a duplicate identifier error instead, which is stricter.
The index-signature gotcha
An object literal type declared with type is implicitly compatible with an index signature. An interface is not, because it could be merged with more members later.
interface UserI {
name: string;
}
type UserT = {
name: string;
};
function printAll(record: Record<string, unknown>): void {
console.log(Object.keys(record));
}
const ui: UserI = { name: "Ada" };
const ut: UserT = { name: "Ada" };
printAll(ut); // fine
// printAll(ui); // error: Index signature for type 'string' is missing in type 'UserI'.This often appears when you pass a typed object to a function that accepts Record<string, unknown> or a generic constraint like T extends Record<string, unknown>. The fixes are to switch the declaration to type, to widen the parameter to object, or to spread the value ({ ...ui }) so a fresh object literal is passed.
Error messages and compiler cost
Hovering over an interface in the editor shows its name, and error messages mention it by name. A complicated alias built from intersections, mapped types, and utility types is often expanded in full in an error message, which can be long.
The TypeScript team has documented that interface extension is usually cheaper for the compiler than intersections. An interface creates a single named object type that the compiler can cache. An intersection must be re-resolved each time it is compared. In small projects you will not notice this. In a large codebase with deep chains of &, it is a reason to prefer interface and extends for object hierarchies.
A decision flow
The last step matters. If none of the earlier questions apply, either choice works, and consistency is worth more than the choice.
Setting a team convention
A convention removes the debate from code review. Two common ones are:
- Interface for object shapes, type for everything else. Public API shapes, class contracts, and anything that might be augmented use
interface. Unions, tuples, function aliases, and derived types usetype. - Type everywhere, interface only when merging is required. This avoids the merging and index-signature surprises and gives the codebase one default keyword.
Either works. Write the rule down, and enforce it with a linter. The @typescript-eslint/consistent-type-definitions rule can require one style for object type declarations.
Library authors have a particular reason to prefer interface for public types. Users of the library can then augment them through merging, which a type alias does not allow.
Common mistakes
- Using
interfacefor a union.interface Result = ...is a syntax error. Usetype Result = A | B. - Expecting intersections to flag conflicts.
&producesneverproperties and does not report an error. Useextendsif you want a conflict reported. - Merging by accident. A repeated interface name in a global script file merges without notice.
- Passing an interface to
Record<string, unknown>. This fails because of the missing implicit index signature (see above). - Mixing styles for the same kind of thing. A codebase with half
interface Propsand halftype Propsmakes readers wonder whether the difference is meaningful.
A worked example
Suppose you model a small event system. Each question below follows the flow above.
// Union of literals: type alias is required.
type EventName = "click" | "hover" | "submit";
// Object shape that other shapes will extend: interface.
interface BaseEvent {
readonly timestamp: number;
name: EventName;
}
interface ClickEvent extends BaseEvent {
name: "click";
x: number;
y: number;
}
interface SubmitEvent extends BaseEvent {
name: "submit";
formId: string;
}
// Union of the object shapes: type alias is required.
type AppEvent = ClickEvent | SubmitEvent;
// Function type: alias is the natural fit.
type Handler<E extends BaseEvent> = (event: E) => void;
const onClick: Handler<ClickEvent> = (e) => {
console.log(`clicked at ${e.x}, ${e.y}`);
};
function dispatch(event: AppEvent): void {
if (event.name === "click") {
onClick(event); // narrowed to ClickEvent
}
}
dispatch({ name: "click", timestamp: Date.now(), x: 10, y: 20 });Each construct is used where it is strongest. Interfaces describe the extendable object shapes, and aliases name the union and the function type. The extends clauses on the two event interfaces would report a conflict if a subtype changed the type of timestamp.
Exercise
A function takes Record<string, unknown>. You pass it a value whose type is declared as interface Settings { theme: string }, and the compiler reports "Index signature for type 'string' is missing in type 'Settings'". Give two ways to fix this without changing the function, and explain why the error occurs.
Show answer
The error occurs because interfaces are open to declaration merging, so TypeScript does not assume an interface has no extra members, and it does not give it an implicit index signature. Object literal types declared with type do get one. Fix 1: declare it as type Settings = { theme: string }. Fix 2: pass a copy built by object spread, fn({ ...settings }), since a fresh object literal is compatible with the index signature.
Exercise
You need a type for a value that is either a Circle object or a Square object, and you want a compile error if a subtype of Shape redefines kind with an incompatible type. Which keyword do you use for the union, which do you use for the hierarchy, and why?
Show answer
Use type Shape = Circle | Square for the union, because only a type alias can name a union. Use interface with extends for the hierarchy (for example interface Circle extends BaseShape). An interface that extends another reports an incompatible property at the declaration. An intersection with & would instead produce a never property and no error.