TS Aliases & Interfaces
TypeScript provides two powerful tools for defining object types: type aliases and interfaces. Both allow you to define the shape of an object, but they have different use cases and capabilities.
Key Topics
Type Aliases
Type aliases allow you to create custom types by using the type
keyword. They can be used for objects, primitives, unions, and more.
type User = {
name: string;
age: number;
};
let user: User = { name: "Alice", age: 25 };
console.log(user.name); // Alice
console.log(user.age); // 25
Output
Alice
25
Explanation: The User
type alias defines an object structure with two properties: name
and age
.
Interfaces
Interfaces define the structure of an object. They are ideal for defining contracts in code and are particularly useful in class-based programming.
interface Vehicle {
brand: string;
model: string;
}
let car: Vehicle = { brand: "Toyota", model: "Corolla" };
console.log(car.brand); // Toyota
console.log(car.model); // Corolla
Output
Toyota
Corolla
Explanation: The Vehicle
interface specifies the required properties brand
and model
.
Extending Interfaces
Interfaces can be extended to inherit properties from other interfaces, promoting reusability.
interface Vehicle {
brand: string;
}
interface Car extends Vehicle {
model: string;
}
let myCar: Car = { brand: "Honda", model: "Civic" };
console.log(myCar.brand); // Honda
console.log(myCar.model); // Civic
Output
Honda
Civic
Explanation: The Car
interface extends the Vehicle
interface, adding the model
property while inheriting brand
.
Key Differences
- Interfaces: Cannot be used for unions or primitives but can be extended and implemented by classes.
- Type Aliases: Can represent objects, unions, primitives, and more but cannot be implemented by classes.
Key Takeaways
- Type Aliases: Useful for defining objects, unions, and complex types.
- Interfaces: Ideal for defining contracts and extending structures.
- Extensibility: Interfaces can be extended, making them more flexible for reuse.
- Use Cases: Choose based on your needs—use interfaces for object shapes and type aliases for flexibility.