-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Dynamic generic type inference for object literals #24375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
So basically, you want to write: Note you can already write
I think all of the above reasons apply just as well to |
Thanks for the comment. I think you make valid points, but in the case where a generic function type can be inferred, the same thing may be required for an object literal. Consider this snippet:
Here TypeScript is able to automatically infer the generic type of the reduce function call as string But now consider the arguments of the reduce function expressed as a generic interface:
Lets say we want to declare a object literal of keyed ReductionArgs objects, where each key value can have a different generic type. The best we can do, currently, is something like:
But now we lost the generic type checking. We could of course explicitly add |
That would be an existential type then? (#14466) |
I think so, in that example I don't care what the generic type is, so long as the object is internally consistent. But that is only one example; I think #17574 comes closer to a comprehensive solution |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
Search Terms
generics, inference, objects
Suggestion
I can define a generic function like so:
const fn = <T>(arg: T)=>Partial<T>
In this case, TypeScript can sometimes infer the type parameter of the function based on the actual parameters I pass it. Is there a similar way to define a generic object literal whose type parameter can be dynamically inferred based on its contents? Something like:
I am aware I can make the interface generic in the usual way like so:
but I want to avoid that, because then I would have to declare the generic type in advance whenever I am using the interface. For example,
const x: XYZ
will not work (unless I provide a default generic parameter type). If I want to make the declaration somewhat general, I am forced to write:
const x: XYZ<any>
but this does not allow TypeScript to dynamically infer the specific generic type based on the actual contents of
x
The text was updated successfully, but these errors were encountered: