1

Here is a a trimmed down example. I'd like to be able to infer the return type without having to explicitly declare the generic type.

interface Animal {
    name : string
}

interface Dog extends Animal {
    goodBoy : boolean
}

class AnimalFood<A extends Animal> {
    feed( animal : A ) {
        // Do something
    }
}

class AnimalStore<A extends Animal> {
    buyFood( animal : A ) {
        // Do something
    }
}

const findFoodStore = <A extends Animal>( food : AnimalFood<A> ) : AnimalStore<A> => {
    return new AnimalStore<A>();
};

const dogStore = new AnimalFood<Dog>();
const animalFood = findFoodStore( dogStore );  // inferred as AnimalStore<Animal>
const dogFood = findFoodStore<Dog>( dogStore );  // inferred as AnimalStore<Dog>
const moreDogFood : AnimalStore<Dog> = findFoodStore( dogStore );  // inferred as AnimalStore<Dog>

The animalFood value does not infer the Dog type. How can I fix this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

0 Answers0