Difference Between Type and Interface in TypeScript
TypeScript provides two ways to define complex types: type aliases and interfaces. Both are widely used but serve different purposes. This guide explains their differences in detail.
What Are Type Aliases?
A type
in TypeScript defines a new name for a type, allowing you to create aliases for complex or union types.
type ID = string | number;
type User = {
name: string;
age: number;
};
What Are Interfaces?
An interface
is a blueprint for object shapes, defining properties and methods.
interface User {
name: string;
age: number;
}
Key Differences Between Type and Interface
Feature | Type | Interface |
---|
Usage | Works with all types. | Defines object structures. |
Extension | Cannot extend another type directly but can achieve similar functionality using intersections (&). | Can extend other interfaces and types. |
Union Types | Supports union types. | Does not support unions. |
Declaration Merging | Not supported. | Supported. |
Example: Extending and Implementing
Using Type:
type Animal = {
name: string;
};
type Dog = Animal & {
breed: string;
};
// Example usage:
const myDog: Dog = {
name: "Buddy",
breed: "Golden Retriever"
};
Using Interface:
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
// Example usage:
const myDog: Dog = {
name: "Buddy",
breed: "Golden Retriever"
};
Using Interface to extend Type:
type Animal = {
name: string;
};
interface Dog extends Animal {
breed: string;
}
Example: Declaration Merging
Interface:
interface User {
name: string;
}
interface User {
age: number;
}
const user: User = { name: "Alice", age: 25 };
Type:
Cannot merge declarations.
Best Practices
- Use
type
for union or primitive types.
- Use
interface
for object shapes and class definitions.
- Prefer
interface
when declaration merging is needed.
Next Steps
Explore real-world scenarios to choose between type
and interface
effectively. Practice combining both for optimal results.
Master the differences to write better, cleaner, and Bug Free TypeScript code!