0
0
Typescriptprogramming~5 mins

Duck typing mental model in TypeScript

Choose your learning style9 modes available
Introduction

Duck typing helps TypeScript check if an object can be used based on its shape, not its exact type name. It makes code flexible and easy to work with.

When you want to accept any object that has certain properties or methods, regardless of its declared type.
When you want to write functions that work with different objects that share similar features.
When you want to avoid strict class inheritance but still ensure objects have needed parts.
When you want to quickly check if an object fits a role by its properties, like a "duck".
When you want to write reusable code that works with many shapes of data.
Syntax
Typescript
interface Quackable {
  quack(): void;
}

function makeItQuack(duck: Quackable) {
  duck.quack();
}
TypeScript checks if the object passed to makeItQuack has a quack method, no matter its actual type name.
This is called structural typing or duck typing: 'If it looks like a duck and quacks like a duck, it is a duck.'
Examples
Here, an object with a quack method is accepted even without explicitly saying it implements Quackable.
Typescript
interface Quackable {
  quack(): void;
}

const duck = {
  quack() {
    console.log('Quack!');
  }
};

makeItQuack(duck);
A class instance with the right method also works because it matches the shape.
Typescript
class Bird {
  quack() {
    console.log('Bird quacks!');
  }
}

const bird = new Bird();
makeItQuack(bird);
An object missing the required method is rejected by TypeScript.
Typescript
const notADuck = {
  swim() {
    console.log('Swimming');
  }
};

// makeItQuack(notADuck); // Error: Property 'quack' is missing
Sample Program

This program shows two different objects with a quack method. Both are accepted by the function because they match the shape.

Typescript
interface Quackable {
  quack(): void;
}

function makeItQuack(duck: Quackable) {
  duck.quack();
}

const duck = {
  quack() {
    console.log('Quack!');
  }
};

const person = {
  quack() {
    console.log('I can quack too!');
  }
};

makeItQuack(duck);
makeItQuack(person);
OutputSuccess
Important Notes

Duck typing focuses on what an object can do, not what it is called.

It helps write flexible and reusable code without strict class hierarchies.

TypeScript uses this to check types by structure, not by name.

Summary

Duck typing means checking if an object has needed properties or methods.

TypeScript uses structural typing to allow flexible code.

If an object looks like a duck and quacks like a duck, TypeScript treats it as a duck.