Interfaces and Types
TypeScript provides two main ways to define custom types: interfaces and type aliases. Understanding when to use each one is key to writing maintainable TypeScript code.
Interfaces
Interfaces define contracts in your code. They specify the shape that objects must follow:
interface Product {
id: number;
name: string;
price: number;
inStock: boolean;
}
// Using the interface
const laptop: Product = {
id: 1,
name: "MacBook Pro",
price: 1299,
inStock: true
};
Type Aliases
Type aliases create new names for types. They can be used for primitives, unions, tuples, and other complex types:
type ID = string | number;
type Status = "pending" | "shipped" | "delivered";
type OrderItem = {
productId: ID;
quantity: number;
status: Status;
};
When to Use Each
Use Interfaces When:
- Defining object shapes
- Creating extensible types
- Working with classes
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log("Woof!");
}
}
Use Type Aliases When:
- Creating unions or intersections
- Defining tuple types
- Creating complex type expressions
type Point = [number, number];
type StringOrNumber = string | number;
type NamedPoints = { [name: string]: Point };
Extending Types
Both interfaces and types can be extended, but with different syntax:
// Extending interfaces
interface BasicProduct {
id: number;
name: string;
}
interface DetailedProduct extends BasicProduct {
description: string;
price: number;
}
// Extending types
type BasicUser = {
id: number;
name: string;
};
type DetailedUser = BasicUser & {
email: string;
role: string;
};
Best Practices
- Prefer interfaces for public APIs
- Use type aliases for complex types and unions
- Be consistent with naming conventions
- Keep interfaces focused and single-purpose
Practice Exercise
Create an interface for a Vehicle with basic properties, then extend it to create specific vehicle types like Car and Motorcycle. Include methods for calculating fuel efficiency.