0
0
Typescriptprogramming~3 mins

Why Duck typing mental model in TypeScript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could use any object just by knowing what it can do, not what it is?

The Scenario

Imagine you have many different objects representing animals, vehicles, or gadgets, and you want to check if they can perform a certain action like quack or drive. Manually checking each object's exact type or class before using it can be confusing and slow.

The Problem

Manually verifying types means writing lots of code to check each object's class or interface. This is slow, error-prone, and makes your code bulky. It also stops you from using objects that behave correctly but don't share the same exact type.

The Solution

Duck typing lets you focus on what an object can do, not what it is. If it has the right properties or methods, TypeScript treats it as the correct type. This makes your code simpler, more flexible, and easier to maintain.

Before vs After
Before
if (obj instanceof Duck) { obj.quack(); } else { throw new Error('Not a duck'); }
After
function makeItQuack(duck: { quack: () => void }) { duck.quack(); }
What It Enables

It enables writing flexible code that works with any object that fits the expected shape, without strict type checks.

Real Life Example

In a drawing app, you can pass any shape object that has a draw() method, whether it's a circle, square, or custom shape, without needing them to share a common class.

Key Takeaways

Duck typing focuses on an object's abilities, not its exact type.

This reduces complex type checks and makes code more flexible.

TypeScript uses this model to allow easy and safe use of objects with matching shapes.