
In TypeScript, interface
and type
are used to define custom types, but they have some differences in their behavior and syntax. Here are the main differences between the two:
Syntax
The syntax for defining an interface is interface
followed by the name of the interface, while the syntax for defining a type is type
followed by the name of the type.
Example:
interface Person {
name: string;
age: number;
}
type Car = {
make: string;
model: string;
year: number;
};
Object Type vs. Alias
An interface
defines a new object type, while a type
defines an alias for an existing type or creates a new one. In other words, an interface creates a new type, while a type alias can be used to give a name to an existing type or to create a union or intersection of types.
Example:
type Age = number;
interface Person {
name: string;
age: Age;
}
type PersonAge = Age; // Alias for number
Extending
An interface can extend one or more other interfaces, while a type can only be extended by creating a new type using union, intersection, or mapped types.
Example:
interface Animal {
type: string;
}
interface Dog extends Animal {
breed: string;
}
type Cat = Animal & {
color: string;
};
Declaration merging
Interfaces support declaration merging, which means that you can define multiple interfaces with the same name and they will be merged into a single interface. Types do not support declaration merging.
Example:
interface User {
name: string;
}
interface User {
email: string;
}
const user: User = {
name: "John",
email: "john@example.com"
};
In summary, interface
is used to define new object types, while type
is used to create aliases for existing types or to create unions, intersections, and mapped types. Interfaces support extending and declaration merging, while types do not. Both interface
and type
can be used to define custom types in TypeScript, and choosing which one to use depends on your use case and personal preference.