TypeScript: ReturnType returns unknown if function's return type is generic argument of the function (with default value) that has not been set
π Search Terms
ReturnType, generic, default
π Version & Regression Information
- This is a crash
- This changed between versions ______ and _______
- This changed in commit or PR _______
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
- I was unable to test this on prior versions because _______
β― Playground Link
No response
π» Code
const func = <Return = string>(): Return {
//
}
type ShouldBeNumber = ReturnType<typeof func<number>>; // number
type ShouldBeString = ReturnType<typeof func>; // unknown
π Actual behavior
ReturnType returns unknown.
π Expected behavior
ReturnType returns default type.
Additional information about the issue
This was encountered when trying to write this kind of function:
const invoker = <Endpoint extends (...args: any) => any>(endpoint: Endpoint, ...parameters: Parameters<Endpoint>): ReturnType<Endpoint> {
// Perform some logic before endpoint function is called
return endpoint(...parameters);
}
About this issue
- Original URL
- State: closed
- Created 4 months ago
- Comments: 15 (2 by maintainers)
Duplicate of #48870.
Is this what youβre looking for?
https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZgVzMGBeGAeASgUyggJzABoA+ACgEoAuGXfItUmAbwCgYYoALAkAdxhgcggKIE+BcgCIAlgFsADgBsc8nGFjrplNgF82UAJ6KcMAGJJgGACqpoBWWADmZNFxM4QceFdulDTxgAZW4QBGUAEwAhHAA5BHkAIxwCd3pCMBtPDEtkDDBElIJSUgBuGAB6SqEi1LZqzhgAPQB+QNMQsIiYnGCoRxd0vEzs01yrcqqahydnBprONqA
That exhibits the same distinction as
One is a generic type (i.e. a type-function) that resolves to a concrete, non-generic function type. The other is the type of a generic function, whose return type is not known until itβs called.
Note that this is the same reason you canβt write
Fun2<number>.I do not think this is working as indented in sense that it might be an intentional side effect but it is frankly stupid to claim that this is βproperβ behaviour that should be upheld.
If this is working
I see no reason why it should not work with functions.