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.
Support My Work ❤️
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me 🌍
Let’s stay connected! You can follow me or reach out on these platforms:
🔹 YouTube – Tutorials, insights & tech content
🔹 LinkedIn – Professional updates & networking
🔹 GitHub – My open-source projects & contributions
🔹 Instagram – Behind-the-scenes & personal updates
🔹 X (formerly Twitter) – Quick thoughts & tech discussions
I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (1)
Thanks for sharing!