Skip to content

Instantly share code, notes, and snippets.

@jjhiggz
Last active April 14, 2025 16:57
Show Gist options
  • Save jjhiggz/f2bfed31b8d731cf891dd7b3286d1726 to your computer and use it in GitHub Desktop.
Save jjhiggz/f2bfed31b8d731cf891dd7b3286d1726 to your computer and use it in GitHub Desktop.
Composition vs Inheritance
// Define individual animal types
type Dog = {
type: "dog";
name: string;
sound: "bark";
};
type Cat = {
type: "cat";
name: string;
sound: "meow";
};
type Duck = {
type: "duck";
name: string;
sound: "quack";
};
// Discriminated union of all animals
type Animal = Dog | Cat | Duck;
// Function to simulate speaking
function speak(animal: Animal): string {
switch (animal.type) {
case "dog":
return `${animal.name} says: ${animal.sound.toUpperCase()}!`;
case "cat":
return `${animal.name} says: ${animal.sound.toUpperCase()}!`;
case "duck":
return `${animal.name} says: ${animal.sound.toUpperCase()}!`;
default:
// This should never happen if all types are covered
return "Unknown animal sound.";
}
}
// Example animals
const dog: Dog = { type: "dog", name: "Rover", sound: "bark" };
const cat: Cat = { type: "cat", name: "Whiskers", sound: "meow" };
const duck: Duck = { type: "duck", name: "Daffy", sound: "quack" };
// Usage
console.log(speak(dog)); // Rover says: BARK!
console.log(speak(cat)); // Whiskers says: MEOW!
console.log(speak(duck)); // Daffy says: QUACK!
// Base class
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): string {
return `${this.name} makes a sound.`;
}
}
// Subclasses with overridden behavior
class Dog extends Animal {
speak(): string {
return `${this.name} says: Bark!`;
}
}
class Cat extends Animal {
speak(): string {
return `${this.name} says: Meow!`;
}
}
class Duck extends Animal {
speak(): string {
return `${this.name} says: Quack!`;
}
}
// Function using polymorphism
function askToSpeak(animal: Animal) {
console.log(animal.speak());
}
// Usage
const dog = new Dog("Rover");
const cat = new Cat("Whiskers");
const duck = new Duck("Daffy");
askToSpeak(dog); // Rover says: Bark!
askToSpeak(cat); // Whiskers says: Meow!
askToSpeak(duck); // Daffy says: Quack!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment