The age-old TypeScript question: "Type vs Interface: When to Use Each?"
Here's a simplified explanation:
Interface
Use for: Defining the shape of objects, including classes.
Typical use cases:
Object literals: When describing the structure of an object with properties, methods, or indexes.
Classes: Extending or implementing interfaces for classes is a common practice, especially for maintaining or enforcing specific structures or contracts (e.g., implementing a printable interface).
Function parameters and return types: When the parameter or return value is an object with specific properties.
Custom types (e.g., combining other types or interfaces)
Typical use cases:
Simplifying complex types: When you have a long union, intersection, or tuple type that you want to reuse.
Creating type aliases for primitives: For readability, especially in contexts where the primitive's meaning is not immediately clear.
Transforming existing types: Use utility types like Partial<T>, Readonly<T>, or Pick<T, K> to modify existing types.
Combining interfaces with other types: When you need a type that extends an interface with additional type information (e.g., an interface plus a primitive).
Type Example:
typescript
// Simplifying a union type
type StringOrNumber = string | number;
// Creating a type alias for better readability
type UserID = number;
// Using utility types to transform an interface
interface User {
name: string;
age: number;
email: string;
}
type PartialUser = Partial<User>; // All properties are optional
type ReadOnlyUser = Readonly<User>; // All properties are readonly
type UserNameAndAge = Pick<User, 'name' | 'age'>; // Only name and age properties
// Combining an interface with a primitive type
type PrintablePerson = Person & { print(): void };
interface Person {
name: string;
age: number;
}
const person: PrintablePerson = {
name: 'John Doe',
age: 30,
print: () => console.log('Printing person info...')
};
In Summary:
Interface is primarily for defining object structures (including classes) with a focus on object-oriented programming (OOP) principles.
Type is for creating reusable aliases for any type (simple or complex), enhancing code readability and maintainability. It also includes advanced use cases like utility types for transforming existing types.
While there's some overlap in their capabilities (e.g., you can extend interfaces from other interfaces, similar to how types can intersect), following these guidelines should help you decide when to reach for interface versus type in TypeScript.