Daily Shaarli

All links of one day in a single page.

December 20, 2025

Note: Duck typing en Javascript

let o = {}
o.quack = (x)=> "quack ! "

//Monkey patching ! My console is now a Duck !
console.quack = (x)=> "quack ! "

let b = {
    quack: (x)=> "quack ! "
}

console.log(b.quack())

// Duck typing :
// if it looks like a duck (i.e has a function called quack())
// if it quacks like a duck
// then it's a duck
// therefore I can call it like a duck
f = (duck)=>console.log(duck.quack())

f(b)
f(o)

f(console)

// It doesn't look like a duck
f({ })
// It doesn't quack like a duck
f({ quack:"foo"})
Note: Duck typing en Typescript
type Duck = {
    type: "duck"
    quack(): string
    beAlive(): void
}
type Sheep = {
    type: "sheep"
    beeh(): string
    beAlive(): void
}

function animalNoise(animal: Duck | Sheep) {
    animal.beAlive()
    animal.quack()
    animal.beeh()

    if (animal.type === "duck") {
        animal.quack()
        animal.beeh()
    }
    if (animal.type === "sheep") {
        animal.quack()
        animal.beeh()
    }
}