You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
My workaround for such cases is, (I'm on my phone so I may make typos)
typeCreateValueResult<T>=({value : T});functioncreateValue<T>(value : T) : CreateValueResult<T>{return{ value };}
So, when I need to use the return type of the generic function, I just use CreateValueResult<T>
No need to introduce new syntax. No need for a new feature. You do lose the return type inference, though.
In my projects, I have many generic functions that compose each other and TS' inference isn't always accurate. So, I have the type declarations to explicitly type them.
I thought I could answer this stackoverflow question with a generic factory function but it fails:
Note : I don't see a way to use the
infer
keyword.Expected behavior:
Having a generic type returned by
ReturnType
type, with a special syntax if necessary.Playground Link:
https://www.typescriptlang.org/play/index.html#src=function%20createItem%3CT%3E(value%3A%20T)%20%7B%0D%0A%20%20%20%20return%20%7B%20value%20%7D%3B%0D%0A%7D%0D%0A%0D%0Atype%20ItemV1a%20%3D%20ReturnType%3Ctypeof%20createItem%3E%3B%20%20%2F%2F%20KO%3A%20%7B%20value%3A%20%7B%7D%3B%20%7D%0D%0Atype%20ItemV1b%3CT%3E%20%3D%20ReturnType%3Ctypeof%20createItem%3E%3B%20%20%2F%2F%20KO%3A%20%3CT%3E%20ignored.%20Still%20%7B%20value%3A%20%7B%7D%3B%20%7D%0D%0Atype%20ItemV1c%3CT%3E%20%3D%20ReturnType%3Ctypeof%20createItem%3CT%3E%3E%3B%20%20%2F%2F%20Compile%20error%0D%0A%0D%0Aconst%20createItemLamdba%20%3D%20%3CT%3E(value%3A%20T)%20%3D%3E%20(%7B%20value%20%7D)%3B%0D%0A%0D%0Atype%20ItemV2a%20%3D%20ReturnType%3Ctypeof%20createItemLamdba%3E%3B%20%20%2F%2F%20KO%3A%20%7B%20value%3A%20%7B%7D%3B%20%7D%0D%0Atype%20ItemV2b%3CT%3E%20%3D%20ReturnType%3Ctypeof%20createItemLamdba%3E%3B%20%20%2F%2F%20KO%3A%20%3CT%3E%20ignored.%20Still%20%7B%20value%3A%20%7B%7D%3B%20%7D%0D%0Atype%20ItemV2c%3CT%3E%20%3D%20ReturnType%3Ctypeof%20createItemLamdba%3CT%3E%3E%3B%20%20%2F%2F%20Compile%20error%0D%0A
The text was updated successfully, but these errors were encountered: