Repository navigation
Improve reverse mapped types inference by creating candidates from concrete index types #51612
Description
Suggestion
🔍 Search Terms
inference, reverse mapped types, schema
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
It would be great if TypeScript could take into account concrete index types when inferring reverse mapped types.
Reverse mapped types are a great technique that allows us to create dependencies between properties in complex objects.
For example, in here we can validate what strings can be used as initial property on any given level of this object. We can also "target" sibling keys (from the parent object) within the on property.
This type of inference starts to break though once we add a constraint to T in order to access some of its known properties upfront. Things like T[K]["type"] prevents T from being inferred because the implemented "pattern matching" isn't handling this case and without a special handling this introduces, sort of, a circularity problem. Note how this doesn't infer properly based on the given argument: here
I think there is a great potential here if we'd consider those accessed while inferring.
📃 Motivating Example
interface QueryFunctionContext<
TQueryKey extends string,
> {
queryKey: TQueryKey
}
type QueryOptions = {
key: string
data?: unknown;
fnData?: unknown;
}
type UseQueriesOptions<T extends ReadonlyArray<QueryOptions>> = {
[K in keyof T]: {
queryKey: T[K]['key']
queryFn?: (
ctx: QueryFunctionContext<T[K]['key']>,
) => Promise<T[K]['fnData']> | T[K]['fnData']
select?: (data: T[K]['fnData']) => T[K]['data']
}
}
declare function useQueries<
T extends ReadonlyArray<QueryOptions>
>(queries: [...UseQueriesOptions<T>]): void;Old example
I understand this this particular example looks complex. I'm merely using it as a motivating example to showcase what I'm trying to do:
- limit what kind of values are possible for the
initialproperty (based on the keys of the inferred object) - make this property available conditionally - it shouldn't be allowed where the
typeproperty of the "current" object is'paralel'
A way simpler demo of the inference algorithm shortcomings for this kind of things has been mentioned above (playground link)
type IsNever<T> = [T] extends [never] ? true : false;
type StateType = "parallel" | "final" | "compound" | "atomic";
type StateDefinition = {
type?: StateType;
states?: Record<string, StateDefinition>;
};
type State<T extends StateDefinition> = (T["type"] extends
| "parallel"
| undefined
? {}
: IsNever<keyof T["states"]> extends false
? { initial: keyof T["states"] }
: {}) & {
type?: T["type"];
states?: {
[K in keyof T["states"]]: State<T["states"][K] & {}> & {
on?: Record<string, keyof T["states"]>;
};
};
};
declare function createMachine<T extends StateDefinition>(config: State<T>): T;
createMachine({
// initial property should be available if there are any nested states and if the `type` of this object is not `'parallel'`
initial: "a",
states: {
a: {},
},
});💻 Use Cases
Schema-like APIs could leverage this a ton:
- we could use is at XState to type our state machines
- libraries related to JSON schema could use this
- I bet that TanStack libraries could think of neat ways to leverage this
- I'm pretty sure that Redux Toolkit could use this instead of "validating things through intersections"
Implementation
I'm willing to work on the implementation but I could use help with figuring out the exact constraints of the algorithm.
I've created locally a promising spike by gathering potential properties on the inference info when the objectType has available index info in this inference round (here) and creating a type out of those when there is no other candidate for it here
Activity
RyanCavanaugh commentedon Dec 1, 2022
A less complex example for novices such as myself would be appreciated, lol 😰. Something that would make sense in a blog post, for example, tends to be pretty compelling.
Andarist commentedon Dec 1, 2022
How about this one:
In here, I restrict the presence of
onproperty within the "current" state - it shouldn't be available on a state of type'final'. I'd like for this reverse mapped type to be inferred as the same type that I provide explicitly hereAndarist commentedon Dec 31, 2022
Ryan Cavanaugh (@RyanCavanaugh) I believe that this proposal has a lot of potential to simplify types of some popular libraries, like React Query, Redux Toolkit, and more.
The most recent example of problems that people struggle with can be found in this thread. At the moment, they resort to recursive conditional types but this technique fails to infer unannotated arguments within tuple elements - this is something that works just great with reverse mapped types. The problem is though that they need to infer multiple different things per tuple element and that isn't possible right now - but it could be, with this proposal implemented.
phryneas commentedon Jan 2, 2023
Ryan Cavanaugh (@RyanCavanaugh) maybe I can provide a "real life" example of where this can be useful - from Redux Toolkit.
At the moment, it kinda works, but our types to enforce this are pretty wonky; there is not much inference, and we already had the case where a TS PR had to be rolled back until we could figure out a fix. Better support from TS would be highly appreciated!
Playground Link
Our problem here is to get consistency within that
reducerWithPrepareNotationdefinition while also being consistent withinreducerWithAnotherPrepareNotation, but having different types between both of them.Andarist commentedon Jan 9, 2023
I was experimenting with #52062 and RTK types. While this PR doesn't implement this feature request here - it already allows me to do quite a lot for some libraries.
I managed to implement most of the requirements mentioned by Lenz Weber-Tronic (@phryneas). I could have made a mistake here or there - but my experiment probably could have been refined with someone more intimate with RTK.
PoC RTK types with #52062
What I've learned in the process is that this feature request here would make it easier to write such types (since we would be able to "merge"
TPrepareMapwithTReducerMap) but it wouldn't be able to replace their "validation" logic without #52062.The main problem is that TS often doesn't infer to type params within intersected types - which I think makes sense in most cases. So to create the return type we actually need to infer separately to
TFullReducersand that can only be done using intersections and the logic from #52062.RyanCavanaugh commentedon Dec 4, 2025
I asked Copilot for a summary of reverse mapped types, since I'm going to have to explain these PRs to the team. I thought it was interesting (and at least useful in terms of links)
The History and Evolution of Reverse Mapped Types in TypeScript
Introduction
Reverse mapped types represent one of TypeScript's most sophisticated type inference mechanisms, allowing the compiler to "reverse engineer" type parameters from mapped type structures. This feature enables powerful patterns for type-safe APIs, particularly in frameworks and libraries that need to infer complex type relationships.
What Are Reverse Mapped Types?
Reverse mapped types are TypeScript's ability to infer a type parameter
Twhen you have a value that matches a mapped type structure like{ [K in keyof T]: SomeType<T[K]> }. Instead of requiring explicit type annotations, TypeScript can work backwards from the provided value to determine whatTmust be.Simple Example
Historical Timeline
Early History (Pre-2018)
The foundational work for reverse mapped types was likely laid during TypeScript 2.1-2.8's development of mapped types and conditional types, though explicit reverse mapping wasn't initially supported.
2018-2019: Display and Recursion Issues
Issue #23897 (May 2018): One of the earliest documented issues with reverse mapped types involved incorrect
typeToStringresults for nested reverse mapped types, causing display problems in tooltips and error messages.PR #28494 (November 2018): Added ellipses (
...) for reverse mapped types in nested positions to improve readability, acknowledging that these types could become unwieldy in error messages.2019: Initial Improvements
PR #31221 (May 2019): Major improvement to reverse mapped types by Anders Hejlsberg, fixing issue #30505. This PR enhanced how TypeScript handles inference for generic function parameters through reverse mapped types, particularly for Vue.js-style component props patterns.
PR #33450 (September 2019): Fixed an issue where reverse mapped types should preserve inferable indexes from their source types.
2020-2021: Tuple Support and Instantiation
PR #41106 (October 2020): Added support for partial reverse mapped inferences with tuple types, significantly expanding the utility of reverse mapped types for variadic type patterns.
PR #42449 (April 2021): Added instantiation rules for reverse mapped types, addressing issue #42385 where deferred conditional types within reverse mapped types weren't being properly evaluated.
PR #44684 (June 2021): A DOM library update that unexpectedly affected reverse mapped type behavior due to readonly attribute additions, showing how sensitive the feature is to type system changes.
2022: Context-Sensitive Function Inference
PR #48538 (April 2022): Major enhancement allowing better inference for context-sensitive functions within object and array literal arguments. This improved left-to-right information flow between context-sensitive functions, which significantly benefited reverse mapped type patterns.
The PR addressed multiple long-standing issues (#25092, #38623, #38845, #38872, #41712, #47599, #48279, #48466) and represented a substantial leap in reverse mapped type capabilities.
2023: Intersection Constraints and Edge Cases
PR #55811 (November 2023): Revolutionary addition of reverse mapped types with intersection constraints by Andrea Simone Costa (jfet97). This PR enabled Excess Property Checking (EPC) on type parameter inference sites.
Previously, TypeScript could reverse three kinds of mapped types:
{ [P in keyof T]: X }{ [P in K]: X }where K is a type parameterThis PR added a fourth case: intersection constraints, allowing patterns like:
PR #55794 (November 2023): Fixed const reverse mapped types to be properly treated as const, improving literal type preservation.
PR #55941 (November 2023): Fixed an issue with reverse mapped type inference when a single type variable is left after inferring from matching types.
2024: Recursion Control and Bug Fixes
PR #57837 (April 2024): Fixed infinite recursion issues with
inferReverseMappedType, preventing stack overflow errors in complex scenarios.PR #54029 (Still Open): Proposes improvements for inference of context-sensitive functions within reverse mapped types, building on the #48538 work.
How Reverse Mapped Types Work
The Core Algorithm
At the heart of reverse mapped types is the
inferReverseMappedTypefunction in the TypeScript checker. The algorithm:Types of Reverse Mappings
1. Homomorphic Mapped Types
Preserves the original structure of T.
2. Constrained Mapped Types
Allows partial selection of properties.
3. Union Constraint Mapped Types
Forces presence of certain properties.
4. Intersection Constraint Mapped Types (Since 5.3)
Prevents excess properties, enabling EPC.
Key Considerations
Left-to-Right Inference: Inference flows from left to right in function arguments. Context-sensitive functions can only use information from:
Const Type Parameters: The
constmodifier on type parameters interacts specially with reverse mapped types, affecting readonly inference and literal type preservation.Recursion Limits: Complex recursive reverse mapped types may hit depth limits, requiring careful structuring to avoid infinite loops or excessive stack depth.
Common Patterns and Use Cases
1. Vue-Style Props Validation
2. Redux-Style State Management
3. Form Validation
Known Limitations and Challenges
1. Nested Context-Sensitive Functions
Inference within nested object structures containing context-sensitive functions remains challenging, particularly within reverse mapped types (Issue #52047, #53018).
2. Circular References
Self-referential types can cause inference to fail or produce
nevertypes in certain patterns (Issue #7022 references in various bugs).3. Excess Property Checking Gaps
Prior to intersection constraints, EPC was inconsistent with reverse mapped types, leading to confusing error messages (Issues #55644, #55645, #55927).
4. Display and Tooling
Complex reverse mapped types can produce unwieldy error messages and poor IntelliSense experiences. The compiler uses special markers like
...to manage display complexity.Recent Open Work (2023-2024)
Several PRs remain open or in backlog, indicating ongoing evolution:
Technical Implementation Notes
Key Source Files
src/compiler/checker. ts: ContainsinferReverseMappedType,resolveReverseMappedTypeMemberssrc/compiler/types.ts: Type definitions includingReverseMappedTypesrc/compiler/tracing.ts: Debugging support for reverse mapped typesPerformance Considerations
Reverse mapped type resolution can be expensive. The compiler implements several optimizations:
Conclusion
Reverse mapped types represent a remarkable achievement in type system design, allowing TypeScript to maintain type safety while enabling ergonomic APIs. The feature has evolved significantly since its implicit introduction, with major milestones in tuple support (2020), context-sensitive function inference (2022), and intersection constraints (2023).
The journey from basic property mapping to sophisticated constraint-based inference with EPC demonstrates TypeScript's commitment to both power and usability. While challenges remain—particularly around nested inference and display of complex types—reverse mapped types continue to be refined and expanded, enabling increasingly sophisticated type-safe patterns in modern TypeScript applications.
References
Note: This analysis is based on public GitHub history. Some internal discussions and design decisions may not be fully captured in public issues and PRs.
RyanCavanaugh commentedon Dec 4, 2025
devanshj commentedon Jan 2, 2026
Stumbled upon this and my two cents are instead of using reverse mapped types and enhancing them it's much easier to write and type-check quantified types. For example the motivating example in the description...
...can be written as this...
...and it's instantly SO MUCH easier to read and understand what's happening. My PR does not fulling enable this yet because we'd need multiple passes of inference (aka #51511). But still it can infer
K(because it only requires one pass)....I strongly think spending time on this is going to be worth it.
Andarist commentedon Jan 2, 2026
You could try to leverage "intra expression sites" inference to avoid multiple passes (see the PR introducing this mechanism: #48538 ). The second inference pass (the one that starts including context sensitive parts of the arguments) uses this to infer from those parts with assigned contextual parameters (and thus potentially from the related return types) before potentially fixing inferred types of type parameters when assigning contextual parameters.
To achieve this, you'd have to expand this algorithm to infer into multiple inference contexts (when the extra ones would come from your quantified types). However, you'd have to appropriately push/pop the correct extra inference contexts onto some stack. I'm doing something similar to that in #54029
devanshj commentedon Jan 2, 2026
I'm not sure I'm smart enough yet to understand all that "intra expression sites" jazz haha... at least for a POC multiple inferences are just easier to do in code... and I think even intra expression sites won't make the cut if you have a lot of "chains" of dependencies like we have here
K -> T -> U(and there could be longer chains).Andarist commentedon Jan 2, 2026
Chains like this would be just OK: TS playground. The only rule to remember is to put the "producer" before "consumer" but that's the same limitation as with positional arguments: TS playground
devanshj commentedon Jan 2, 2026
Oh that's really cool didn't know that!