Introduction to Duck Typing in TypeScript



What is Duck Typing?

Duck Typing is usually used in code that needs to handle a range of different data, often without knowing exactly what parameters will be passed by a caller. Think here of some of the uses you encountered for switch statements or complex if/else blocks. These are typically places where Duck Typing might come in handy or even offer an alternative.


Why Duck Type?

A common pattern for duck typing in dynamic languages is to try and perform an action assuming a given value fits what we expect, and then handle whatever exceptions might arise. Python is a good example here:

from typing import Any

def is_duck(value: Any) ->bool:
    try:
        value.quack()
        return True
    except (Attribute, ValueError):
        return False

This is evidently a silly example, but the point is simple — you get a value, you check if it quacks by calling its .quack() method- if it quacks, return true, if either an attribute or value error is raised, return false.