Types vs Interfaces
Types vs Interfaces
Section titled βTypes vs InterfacesβWhat it means
Section titled βWhat it meansβtype aliases and interfaces can both describe object shapes, and for simple cases theyβre nearly interchangeable β but they have real differences. interfaces support declaration merging (redeclaring the same interface adds to it) and are generally preferred for public object/class APIs; type aliases can represent things interfaces canβt, like unions, tuples, and mapped types, and are generally preferred for those cases.
Examples
Section titled βExamplesβ// Both can describe an object shapeinterface UserInterface { name: string; age: number; }type UserType = { name: string; age: number };
// Interfaces merge automatically when declared twice (useful for extending libraries)interface Window { myGlobal: string; }interface Window { anotherGlobal: number; } // merges with the one above
// type aliases can do things interfaces can't:type Status = "loading" | "success" | "error"; // uniontype Coordinates = [number, number]; // tupletype Nullable<T> = T | null; // generic aliastype Readonly<T> = { readonly [K in keyof T]: T[K] }; // mapped type
// Extending: interfaces use `extends`, types use `&`interface Employee extends UserInterface { id: string; }type EmployeeType = UserType & { id: string };Common mistake
Section titled βCommon mistakeβTrying to declare a union or tuple type as an interface β interfaces can only describe object (and function-call) shapes, not unions of unrelated types.
// Error: an interface cannot represent a unioninterface Status = "loading" | "success" | "error"; // not valid syntax at all
// Correct -- use a type alias for unionstype Status = "loading" | "success" | "error";Quick practice
Section titled βQuick practiceβ-
What can a
typealias represent that aninterfacecannot?Answer
Unions, tuples, primitive aliases, and mapped/conditional types β interfaces are limited to describing object and function-call shapes. -
What happens if you declare the same
interfacename twice in the same scope?Answer
TypeScript merges the two declarations into one combined interface (declaration merging) β declaring the sametypealias twice, by contrast, is a compile error. -
How do you extend an existing shape with each β
interfaceversustype?Answer
Interfaces useinterface B extends A { ... }; type aliases use an intersection:type B = A & { ... }.