user1032752
user1032752

Reputation: 871

Properly handling TypeScript's weak type detection

Given this simplified example, what's the proper way to express that the function makeAnimalBark can accept any animal but only makes the barking ones bark.

interface Dog {
    bark: () => void
}

interface Cat {
    meow: () => void
}

interface PotentiallyBarkingAnimal {
    bark?: () => void
}

// Without `A` extending from something that has a `bark`
// property, TS complains that `bark` doesn't exist on `A`.

function makeAnimalBark<A extends PotentiallyBarkingAnimal>(animal: A) {
    if (animal && animal.bark)
        animal.bark()
}

makeAnimalBark<Dog>({
    bark: () => { }
})

// Here, TS complains that `Cat` has no properties
// in common with `PotentiallyBarkingAnimal`.

makeAnimalBark<Cat>({
    meow: () => { }
})

I understand why I'm seeing the error but I'm not sure as to the right way to handle this type of situation.

Upvotes: 0

Views: 110

Answers (1)

Martin Broder
Martin Broder

Reputation: 335

// Without `A` extending from something that has a `bark`
// property, TS complains that `bark` doesn't exist on `A`.

That is because you are typing bark as being optional

interface PotentiallyBarkingAnimal {
    // remove the ? to make bark mandatory
    bark?: () => void
}
// Here, TS complains that `Cat` has no properties
// in common with `PotentiallyBarkingAnimal`.

Well that's true, right? if you look at it Cats interface, it has no shared properties (bark) with PotentiallyBarkingAnimal. You need to let PotentiallyBarkingAnimal know about meow.

Upvotes: 1

Related Questions