The new ReturnType
in TypeScript 2.8 is a really useful feature that lets you extract the return type of a particular function.
function foo(e: number): number {
return e;
}
type fooReturn = ReturnType<typeof foo>; // number
However, I'm having trouble using it in the context of generic functions.
function foo<T>(e: T): T {
return e;
}
type fooReturn = ReturnType<typeof foo>; // type fooReturn = {}
type fooReturn = ReturnType<typeof foo<number>>; // syntax error
type fooReturn = ReturnType<(typeof foo)<number>>; // syntax error
Is there a way extract the return type that a generic function would have given particular type parameters?
If you want to get some special generic type, You can use a fake function to wrap it.
const wrapperFoo = () => foo<number>()
type Return = ReturnType<typeof wrapperFoo>
More complex demo
function getList<T>(): {
list: T[],
add: (v: T) => void,
remove: (v: T) => void,
// ...blahblah
}
const wrapperGetList = () => getList<number>()
type List = ReturnType<typeof wrapperGetList>
// List = {list: number[], add: (v: number) => void, remove: (v: number) => void, ...blahblah}