In TypeScript, both interface
and type
are used to define shapes or structures for values. They are often used interchangeably, but there are some subtle differences between them.
Interfaces:
-
Declaration Merging:
- Interfaces support declaration merging. This means that if you define two interfaces with the same name, TypeScript will merge them into a single interface. This allows you to spread the definition of an interface across multiple files.
interface Person {
name: string;
}
interface Person {
age: number;
}
const john: Person = {
name: 'John',
age: 25,
};
-
Extending:
- Interfaces can extend other interfaces using the
extends
keyword.
- Interfaces can extend other interfaces using the
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
const square: Square = {
color: 'red',
sideLength: 5,
};
Types:
-
Union and Intersection:
- Types can be used to create union and intersection types more easily.
type Status = 'active' | 'inactive';
type Employee = {
id: number;
name: string;
};
type EmployeeStatus = Employee & { status: Status };
-
Mapped Types:
- Types allow the use of mapped types, which can dynamically create new types based on the properties of an existing type.
type Partial<T> = {
[P in keyof T]?: T[P];
};
interface Person {
name: string;
age: number;
}
type PartialPerson = Partial<Person>;
-
Tuple Types:
- Types can represent tuples with specific element types and lengths.
type Point = [number, number];
const coordinates: Point = [10, 20];
In general, interfaces are often preferred for defining object shapes, while types are more versatile and can be used for a wider range of scenarios. The choice between them often comes down to personal preference or specific use cases. It's common to see a mix of interfaces and types in a TypeScript codebase.
If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!
Disclaimer: This content has been generated by AI.