Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface typetypescript
interface Point { x: number; y: number; }
could be written as the type aliaside
type Point = { x: number; y: number; };
Both can be used to describe the shape of an object or a function signature. But the syntax differs.code
Interfaceip
interface Point { x: number; y: number; } interface SetPoint { (x: number, y: number): void; }
Type aliasget
type Point = { x: number; y: number; }; type SetPoint = (x: number, y: number) => void;
Unlike an interface, the type alias can also be used for other types such as primitives, unions, and tuples.string
// primitive type Name = string; // object type PartialPointX = { x: number; }; type PartialPointY = { y: number; }; // union type PartialPoint = PartialPointX | PartialPointY; // tuple type Data = [number, string];
Both can be extended, but again, the syntax differs. Additionally, note that an interface and type alias are not mutually exclusive. An interface can extend a type alias, and vice versa.it
Interface extends interfaceio
interface PartialPointX { x: number; } interface Point extends PartialPointX { y: number; }
Type alias extends type aliasfunction
type PartialPointX = { x: number; }; type Point = PartialPointX & { y: number; };
Interface extends type aliasclass
type PartialPointX = { x: number; }; interface Point extends PartialPointX { y: number; }
Type alias extends interface
interface PartialPointX { x: number; } type Point = PartialPointX & { y: number; };
A class can implement an interface or type alias, both in the same exact way. Note however that a class and interface are considered static blueprints. Therefore, they can not implement / extend a type alias that names a union type.
interface Point { x: number; y: number; } class SomePoint implements Point { x = 1; y = 2; } type Point2 = { x: number; y: number; }; class SomePoint2 implements Point2 { x = 1; y = 2; } type PartialPoint = { x: number; } | { y: number; }; // FIXME: can not implement a union type class SomePartialPoint implements PartialPoint { x = 1; y = 2; }
Unlike a type alias, an interface can be defined multiple times, and will be treated as a single interface (with members of all declarations being merged).
// These two declarations become: // interface Point { x: number; y: number; } interface Point { x: number; } interface Point { y: number; } const point: Point = { x: 1, y: 2 };