Last active
September 23, 2025 10:49
-
-
Save JesusTheHun/935569ed4962cca3ef7b23d035c96e2f to your computer and use it in GitHub Desktop.
Partial Type Argument Inference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| declare function get<Doc, Key extends keyof Doc = infer>(); | |
| declare let unknownObj: unknown; | |
| declare let obj: { title: string; description: string }; | |
| // CASE 0 | |
| const case0 = get(obj, 'description'); | |
| // Unchanged: string | |
| // CASE 1 | |
| const case1 = get<{ title: string; description: string }>(unknownObj, 'description'); | |
| // Current: TS Error | |
| // Proposal: string | |
| // CASE 2 | |
| const case2 = get<{ title: string; description: string }, 'title'>(unknownObj, 'description'); | |
| // Current: ❌ missing type argument | |
| // Proposal: ❌ 'description' cannot be assigned to 'title' | |
| // CASE 3 | |
| // Currently, you have to write | |
| declare function floatingGenericTypeArgument<A, B = any>(b: B): [A, B] | |
| // With this proposal, you could write | |
| declare function floatingGenericTypeArgument<A, B = infer>(b: B): [A, B] | |
| const case3 = floatingGenericTypeArgument<'a'>(null); | |
| // Current: ['a', any] | |
| // Proposal: ['a', null] |
Author
Not sure if you're interested in use-cases, but for your third scenario:
- My function needs a Type that cannot be inferred from the function parameters, hence I need to add a generic type param
- Of one of the function params the type needs to be inferred exactly (Is an Object literal that uses
satisfies) for processing and determining the return type based on specific properties in the Object. As such, I need to both store it as a type parameter, but cannot give it a default, leaving me only the option of additional code as the callsite: myFn<firstType, typeof paramValue>(paramValue)
I think your = infer suggestion would solve my challenge, but I wonder if TS could not support it out of the box without any new syntax, by allowing type parameters from not being specified at the callsite if they are tied to mandatory parameters:
declare function myFn<one, two, true = Object>(a: two, b?: three);
myFn(someValueFromWhichToInferTwo);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Submit your case with the following :