In TypeScript, both interfaces and types serve similar purposes: they define the structure of an object. However, there are some key differences between the two, and I will give an example to illustrate that.
Syntax: The syntax for defining an interface and a type is different. An interface is defined using the "interface" keyword, while a type is defined using the "type" keyword. In this example, we have defined the same object structure using both interface and type.
interface Point { x: number; y: number; } type Point = { x: number; y: number; }
Implementation details: An interface only defines the structure of an object, without providing any implementation details. On the other hand, a type can also include implementation details, such as default values for properties or implementation for methods.
In this example, the interface Point defines the method distance, but it doesn't provide the implementation. On the other hand, the type Point provides the implementation for the distance method.
interface Point { x: number; y: number; distance(): number; } type Point = { x: number; y: number; distance: () => number; }
Extending: Interfaces can be extended, meaning that you can create a new interface that inherits the properties and methods of an existing interface. Types, on the other hand, cannot be extended in the same way.
In this example, we are creating a new interface Point3D that inherits the properties and methods from the Point interface. On the other hand, the type Point3D is created by merging the Point type with an object that has a z property.interface Point3D extends Point { z: number; } type Point3D = Point & { z: number; }
Function Signatures: Types can be used for describing the shape of a function, and that is where it differs from interfaces. The interface can only describe the shape of an object.
type addFn = (a: number, b: number) => number; const add: addFn = (a, b) => a + b; interface addFn { (a: number, b: number): number; } const add: addFn = (a, b) => a + b;
Usage: Interfaces are typically used to define the structure of objects that will be used throughout the application, while types are used to define specific values or groups of values.
In summary, interfaces and types in TypeScript serve similar purposes but have some key differences. Interfaces define the structure of an object without providing implementation details, while types can include implementation details, and are used to define specific values or groups of values. Use interfaces when you want to ensure that an object conforms to a specific structure, and use types when you want to define a specific value or group of values.