Imagine having a setup like this:
type GetDog = () => { animal: string; bark: boolean };
const getDog: GetDog = () => ({ animal: 'dog', bark: true });
type GetCat = () => { animal: string; meow: boolean };
const getCat: GetCat = () => ({ animal: 'cat', meow: true });
type AnimalFactory =
| ((callback: GetDog) => ReturnType<typeof getDog>)
| ((callback: GetCat) => ReturnType<typeof getCat>);
const calmAnimalFactory: AnimalFactory = (callback) => {
// Some fancy stuff
return callback();
};
calmAnimalFactory
should accept either getDog
or getCat
function as an argument, and then return the corresponding value. However, there seems to be an issue with type inference. The callback inside calmAnimalFactory
is not inferring the type of GetDog | GetCat
, but instead defaults to any
. Ideally, I expected Typescript to determine the type of calmAnimalFactory
so that calmAnimalFactory(getDog)
would be typed as
((callback: GetDog) => ReturnType<typeof getDog>)
and calmAnimalFactory(getCat)
would be typed as
((callback: GetCat) => ReturnType<typeof getCat>)
I believe this is achievable, but for some reason it's not working as expected.