Are you new to TypeScript and wondering about the difference between types and interfaces? Let's break it down with some cool examples!
🔹 Types: The Swiss Army Knife.
Types in TypeScript are super flexible. They're like the Swiss Army knife of type definitions.
// Define an object type for a superhero
type Superhero = {
name: string;
power: string;
flyable?: boolean; // Optional property
};
// Create a union type for a limited set of color options
type Color = "red" | "blue" | "green";
// Define a function type for mathematical operations
type MathFunction = (x: number, y: number) => number;
🔹 Interfaces: The Blueprint
Interfaces are like blueprints for objects. They're great for defining the structure of classes.
// Define an interface for a vehicle
interface Vehicle {
brand: string;
speed: number;
accelerate(): void; // Method signature
}
// Implement the Vehicle interface in a Car class
class Car implements Vehicle {
brand: string;
speed: number;
constructor(brand: string) {
this.brand = brand;
this.speed = 0;
}
// Implement the accelerate method
accelerate() {
this.speed += 10;
}
}
🔥 Key Differences:
- Union Types: Only possible with 'type'
// Union type (only possible with 'type')
type Status = "pending" | "approved" | "rejected";
- Extending: Both can extend, but interfaces are more natural for OOP
// Extending an interface
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
// Extending a type
type Shape = {
color: string;
}
type Circle = Shape & {
radius: number;
}
- Declaration Merging: Only interfaces can be reopened to add new properties.
// Declaration merging (only possible with interfaces)
interface Book {
title: string;
}
interface Book {
author: string;
}
// Now Book has both title and author properties
💡 Dev Tip: Use interfaces for objects and classes, and types for functions, unions, and complex types.
Remember, whether you use types or interfaces, TypeScript has got your back in catching errors before runtime!
Top comments (0)