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.
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.
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’
type Status = “pending” | “approved” | “rejected”;
Extending: Both can extend, but interfaces are more natural for OOP
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.
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!