Interface
Interfaces describe the shape of an object the properties and methods it must have.
Basic shape
Optional and readonly properties
Methods
Extending interfaces
An interface can extend one or more other interfaces, inheriting their members:
Index signatures
Used when you don't know all the property names ahead of time, but you know the shape of the keys and values:
Declaration merging
Unlike type, declaring the same interface name twice merges the declarations instead of throwing an error. This is mostly used to extend types from external libraries:
interface vs type
Both can describe the shape of an object, and for everyday use they're mostly interchangeable. A few differences worth knowing:
interfacecan be extended and merged (multiple declarations combine);typecannot be redeclared.typecan describe unions, intersections, tuples, and primitives directly (e.g.type ID = string | number);interfacecan only describe object shapes.- Interfaces are generally preferred for public object/library shapes, since they merge cleanly and tend to give clearer error messages;
typeis preferred for unions, and mapped/conditional types.
See Type for more on type aliases.