'How to evaluate the return type of a function dynamically?
I've got the following code:
// some interfaces to check
interface Car {
name: string;
color: string;
}
interface Bike {
wheels: number;
}
// magic function that simplifies things
function getItems<Fn extends (...args: any[]) => ReturnType<Fn>>( // <- this apparantly doesn't work (ReturnType<Fn>)
getItemsFunc: Fn,
item: ReturnType<Fn> | null
) {
const getItem = () => {
getItemsFunc().then((newItem) => (item = newItem)); // typescript complains here but should not complain here but in the last line
};
getItem();
}
// api call function that returns a promise. functions like this will be put into getItems()
function getCars(): Promise<Car[]> {
// this would be an api call
return new Promise(function (resolve) {
resolve([{name: 'Mustang', color: 'red'}])
})
}
// getItems will be used like this:
const cars: Car[] | null = null;
getItems(getCars, cars);
// i want typescript to complain about this:
const bikes: Bike[] | null = null;
getItems(getCars, bikes); // <- getCars and bikes don't fit each other based on the types
How can I make typescript complain about the last line? But it should not complain about anything else.
I've put the code into the playground, see: Typescript Playground
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
