In TypeScript, both type
and interface
are used to define custom types, but they have some differences and specific use cases where one might be preferred over the other.
When to Use type
Over interface
Union Types:
type can represent union types, where a type can be one of several possible types.
Example:
type Status = "success" | "failure" | "pending";
Intersection Types:
type can be used to combine multiple types into one using the
&
operator.Example:
type Admin = { name: string; role: "admin"; }; type User = { name: string; role: "user"; }; type AdminUser = Admin & User;
More Complex Types:
type can handle more complex types, such as tuples, mapped types, and more.
Example:
type Point = [number, number];
Primitive Types:
type can create an alias for any kind of type, including primitives.
Example:
type ID = string | number;
Cannot be Merged:
Unlike interface, type cannot be merged or extended by subsequent declarations, making it safer in scenarios where you don't want unintended extension or merging.
When to Use interface
Object Type Declarations:
interface is more suited for defining the shape of an object, particularly when you want to describe an object with methods.
Example:
interface User { name: string; age: number; greet(): void; }
Extending and Implementing:
interface supports easy extension and can be implemented by classes.
Example:
interface Animal { name: string; makeSound(): void; } interface Dog extends Animal { breed: string; }
Declaration Merging:
interface can be merged with another interface of the same name, which can be useful in extending third-party types.Example:
interface User { name: string; } interface User { age: number; } const user: User = { name: "Alice", age: 30, };
Summary
- Use type when you need to create more complex types, such as unions, intersections, or primitive type aliases.
- Use interface when you are defining the shape of an object, especially if you plan to use classes or need the flexibility of extension and merging.