In TypeScript, both interfaces and types are used to define custom data structures, but there are some differences in their capabilities and use cases. Here are the key distinctions between interfaces and types:
Interfaces:
-
Declaration Merging:
- Interfaces in TypeScript support declaration merging. This means that if you declare two interfaces with the same name, they will be merged into a single interface.
interface Person {
name: string;
}
interface Person {
age: number;
}
// Merged into a single interface
// Resulting interface: { name: string; age: number; }
-
Extending Interfaces:
- You can extend other interfaces using the
extends
keyword.
- You can extend other interfaces using the
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
-
Implementing Classes:
- Interfaces can be used to define the shape of a class and ensure that a class adheres to a particular structure.
interface Printable {
print(): void;
}
class Document implements Printable {
print() {
console.log("Printing document...");
}
}
Types:
-
Union and Intersection:
- Types in TypeScript can represent union and intersection types, allowing you to create complex types by combining multiple types.
type UnionType = string | number;
type IntersectionType = { prop1: string } & { prop2: number };
-
Support for Primitives:
- Types can represent primitive types directly.
type Age = number;
-
Mapped Types:
- Types can be used to create mapped types, allowing you to transform the properties of an existing type.
type Optional<T> = {
[P in keyof T]?: T[P];
};
-
Tuple Types:
- Types can be used to define tuple types.
type Point = [number, number];
When to Choose:
-
Use Interfaces When:
- You want to represent the shape of an object or define contracts for classes.
- You need declaration merging or want to extend other interfaces.
-
Use Types When:
- You need to create union or intersection types.
- You want to create mapped types or define complex types.
- You are working with primitive types or tuple types.
In many cases, interfaces and types can be used interchangeably, and the choice between them often comes down to personal preference or specific use-case requirements.
Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and Typescript, as well as contribute to open-source projects and learning Typescript. I am currently seeking a remote job.
Twitter: https://twitter.com/Diwakar_766
GitHub: https://github.com/DIWAKARKASHYAP
Portfolio: https://diwakar-portfolio.vercel.app/
Top comments (2)
Hi DIWAKARKASHYAP!
Great article, very useful
Thanks for sharing
I'm glad you found the article useful! If you have any questions or need further clarification on anything, feel free to ask. Happy to help!