Title: Feature request: Dependent contextual inference · Issue #64091 · microsoft/TypeScript · GitHub
Open Graph Title: Feature request: Dependent contextual inference · Issue #64091 · microsoft/TypeScript
X Title: Feature request: Dependent contextual inference · Issue #64091 · microsoft/TypeScript
Description: 🔍 Search Terms Dependent contextual inference, self type checking types, can't infer type parameters from context-sensitive expressions, self referencing types ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScri...
Open Graph Description: 🔍 Search Terms Dependent contextual inference, self type checking types, can't infer type parameters from context-sensitive expressions, self referencing types ✅ Viability Checklist This wouldn't b...
X Description: 🔍 Search Terms Dependent contextual inference, self type checking types, can't infer type parameters from context-sensitive expressions, self referencing types ✅ Viability Checklist This wouldn...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/64091
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Feature request: Dependent contextual inference","articleBody":"### 🔍 Search Terms\n\nDependent contextual inference, self type checking types, can't infer type parameters from context-sensitive expressions, self referencing types\n\n### ✅ Viability Checklist\n\n- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code\n- [x] This wouldn't change the runtime behavior of existing JavaScript code\n- [x] This could be implemented without emitting different JS based on the types of the expressions\n- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)\n- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types\n- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals\n\n### ⭐ Suggestion\n\nTo keep it really terse the feature request (which I'm calling \"dependent contextual inference\") is when a contextual type of an expression is in the form `T extends F\u003cT>` perform `n` checks each with contextual type `T extends F\u003cTn-1>` where `Tn-1` is the type of the expression after check `n-1` for `n > 1` and `T` for `n = 1` until the `Tn` is identitcal to `Tn-1` or `n >= 5`\n\nLet's take an example...\n\n```ts\ndeclare const f:\n \u003cT extends { a: unknown, b: (a: T[\"a\"]) => unknown }>\n (t: T) =>\n ReturnType\u003cT[\"b\"]>\n \nconst r = f({\n a: \"hello\",\n b: a => a.toUpperCase()\n// ~\n// 'a' is of type 'unknown'. (18046)\n})\n```\n\nToday `a` is inferred as `unknown` that's because there's just two passes of check that happen, in the first pass the object literal is inferred as `{ a: string, b: anyFunctionType }` and because it's effectively a non-inferrable type as it contains an `anyFunctionType`, `T` has no inference candidates leading `T` to be inferred with it's constraint... and the second pass just happens with `T` being fixed to what was inferred in the first pass ie as if the user has written `f\u003c{ a: unknown, b: (a: unknown) => unknown }>(...)`.\n\nWith dependent contextual inference the first pass remains the same and the object literal's type is inferred as `{ a: string, b: anyFunctionType }` but the second pass happens with the contextual type as `T extends { a: unknown: b: (a: { a: string, b: anyFunctionType }[\"a\"]) => unknown }` and now object literal's type becomes `{ a: string, b: (a: string) => string }`, and checker does one more pass with contextual type `T extends { a: unknown, b: (a: { a: string, b: (a: string) => string }[\"a\"]) }` resulting the object literal's type being the same as before and the checker stops as the last two checks produced identical types. And finally `T` is inferred as `{ a: string, b: (a: string) => string }`. And the checker does one final check with `T` being fixed to that as if the user had written `f\u003c{ a: string, b: (a: string) => string }>(...)`.\n\nI've implemented a shabby version in PR #64092 but maybe there's a better way to implement it.\n\n### 📃 Motivating Example\n\nImagine you have a state machine like library written in javascript...\n\n```js\nconst runMachine = (definition) => {\n let { state, context } = definition.initial\n while (true) {\n if (state === undefined) break;\n const next = definition.transitions[state]({ context })\n state = next?.state\n context = next?.context\n }\n return { state, context }\n}\n\nconst result = runMachine({\n initial: {\n state: \"loggedOut\",\n context: {}\n },\n transitions: {\n loggedOut: ({ context }) => {\n return { state: \"loggingIn\", context: { username: \"devanshj\", password: \"1234\" } }\n },\n loggingIn: ({ context }) => {\n if (context.username === \"devanshj\" && context.password === \"1234\") {\n return { state: \"loggedIn\", context: { ...context, accessToken: \"whatever\" } }\n } else {\n return { state: \"loggedOut\", context: { failedOnce: true } }\n }\n },\n loggedIn: ({ context }) => {\n console.log(context.accessToken)\n }\n }\n})\n```\n\nAnd now you want to write types for it... Today the best typings look like this (with a little change in api ie the double invocation `runMachine()(...)`)...\n\n```ts\ndeclare const runMachine:\n \u003cTMachine extends { state: string, context: object }>() =>\n \u003cTDefinition extends {\n initial: TMachine,\n transitions: {\n [S in TMachine[\"state\"]]:\n (parameter: { context: Extract\u003cTMachine, { state: S }>[\"context\"] }) => void | TMachine\n }\n }>\n (definition: TDefinition) =>\n TMachine\n\n\nconst result = runMachine\u003c\n | { state: \"loggedOut\", context: {} | { failedOnce: boolean } }\n | { state: \"loggingIn\", context: { username: string, password: string } }\n | { state: \"loggedIn\", context: { username: string, password: string, accessToken: string, failedOnce?: boolean } }\n>()({\n initial: {\n state: \"loggedOut\",\n context: {}\n },\n transitions: {\n loggedOut: ({ context }) => {\n return { state: \"loggingIn\", context: { username: \"devanshj\", password: \"1234\" } }\n },\n loggingIn: ({ context }) => {\n if (context.username === \"devanshj\" && context.password === \"1234\") {\n return { state: \"loggedIn\", context: { ...context, accessToken: \"whatever\" } }\n } else {\n return { state: \"loggedOut\", context: { failedOnce: true } }\n }\n },\n loggedIn: ({ context }) => {\n console.log(context.accessToken)\n }\n }\n})\n```\n\nThis is the best because the expectation is that the final result is a discriminated union so that when you do `if (result.state === \"loggedIn\")` it narrows the result and the context in a way you can read `accessToken` from the context which is gauranteed by the logic. Another expectation is that each transition receives the `context` in the shape that is again gauranteed by the definition logic eg `loggingIn` must receive a context where `username` and `password` are defined because each `loggedOut` sends it.\n\nSo any other easy solution (eg the following) won't work...\n\n```ts\ndeclare const runMachine:\n \u003cTState extends string, TContext extends object>\n (definition: {\n initial: { state: TState, context: TContext },\n transitions:\n Record\u003c\n TState,\n (current: { context: TContext }) => void | { state: TState, context: TContext }\n >\n }) =>\n { state: TState, context: TContext }\n```\n\nNow in theory we can type it like this...\n\n```ts\ndeclare const runMachine:\n \u003cTDefinition extends {\n initial: {\n state: keyof TDefinition[\"transitions\"],\n context: object\n },\n transitions: {\n [TState in keyof TDefinition[\"transitions\"]]:\n (current: { context: Context\u003cTDefinition, TState> }) =>\n | void\n | { state: keyof TDefinition[\"transitions\"], context: object }\n }\n }>\n (definition: TDefinition) =>\n { [S in keyof TDefinition[\"transitions\"]]: { state: S, context: Context\u003cTDefinition, S> } }[keyof TDefinition[\"transitions\"]]\n\n// iterative over all transitions and collect the context for the given state\ntype Context\u003cTDefinition extends Definition, TState> =\n | { [S in keyof TDefinition[\"transitions\"]]:\n ReturnType\u003cTDefinition[\"transitions\"][S]> extends infer R\n ? R extends unknown\n ? R extends { state: TState, context: infer C }\n ? C\n : never\n : never\n : never\n }[keyof TDefinition[\"transitions\"]]\n | (TDefinition[\"initial\"][\"state\"] extends TState\n ? TDefinition[\"initial\"][\"context\"]\n : never)\n\n// just to satisfy the type checker\ntype Definition =\n { initial: { state: keyof any, context: object }, transitions: Record\u003ckeyof any, (...a: never) => unknown> }\n```\n\nThe result? It works exactly like the manually annotated one (ie each transition gets the context it would expect and the final result is a discriminated union) and the user has to write zero type annotations...\n\n\u003cimg width=\"721\" height=\"658\" src=\"https://github.com/user-attachments/assets/3b238d28-650f-41da-900f-a1cf428483f6\" />\n\nThe only caveat is that it relies on dependent contextual inference and doesn't actually work today.\n\n### 💻 Use Cases\n\nBecause any generic signature can be rewritten in form of `T extends F\u003cT>` and leverage dependent contextual inference, a lot of problems can be solved, here are few...\n\n1. Inferring invariant generics\n\nLet's take a simple example...\n\n```ts\ndeclare const update:\n \u003cT>(f: (previous: T) => T) => T\n\nupdate(previous => ({ count: typeof previous.count === \"number\" ? previous.count + 1 : 0 }))\n```\n\nHere `previous` in inferred as `unknown` so this doesn't compile. But it can be refactored to `T extends F\u003cT>`...\n\n```ts\ndeclare const update:\n \u003cT extends (previous: ReturnType\u003cT>) => unknown>(f: T) => ReturnType\u003cT>\n\nupdate(previous => ({ count: typeof previous.count === \"number\" ? previous.count + 1 : 0 }))\n```\n\nHere `previous` is inferred as `{ count: number }` and it compiles. It also gracefully handles infinite loops...\n\n```ts\ndeclare const update:\n \u003cT extends (previous: ReturnType\u003cT>) => unknown>(f: T) => ReturnType\u003cT>\n\nudpate(lol => ({ lol }))\n// ~~~~~~~~~~~~~~~~~\n// Dependent contextual inference requires too many passes and possibly infinite\n```\n\nHowever the user can use getters if they meant to a circular shape which would infer a recursive type...\n\n```ts\ndeclare const update:\n \u003cT extends (previous: ReturnType\u003cT>) => unknown>(f: T) => ReturnType\u003cT>\n\nconst x = udpate(lol => ({ get lol() { return lol } }))\nx.lol.lol.lol.lol.lol.lol // compiles\n```\n\nA popular user of invaraint generic would be [zustand](https://github.com/pmndrs/zustand)...\n\n```ts\ndeclare const create:\n \u003cT extends\n ( set: Store\u003cReturnType\u003cT>>[\"set\"]\n , get: Store\u003cReturnType\u003cT>>[\"get\"]\n ) => unknown\n >\n (t: T) =>\n Store\u003cReturnType\u003cT>>\n \ninterface Store\u003cT>\n { get: () => T\n , set: (value: Partial\u003cT>) => void\n }\n\nconst store = create((set, get) => ({\n count: 0,\n increment: () => set({ count: get().count + 1 })\n}))\n```\n\nToday `store` is inferred as `Store\u003cunknown>` hence zustand requires it's users to explicitly type the generic with `create\u003cT>()(...)`, but with dependent contextual inference `store` can be inferred as `Store\u003c{ count: number, increment: () => void }>`\n\n2. Inferring m times n generics\n\nToday we already do a good job of inferring a chain of n-generics...\n\n```ts\ndeclare const useQuery:\n \u003cK, T, U>\n (query: { key: K, fetch: (key: K) => T, select: (data: T) => U }) => U\n\nconst result = useQuery({\n key: \"0\",\n fetch: key => +key,\n select: data => [data]\n})\n```\n\nBut because we don't have existential types it's hard to support m times n generics... Except in theory we can rewrite them in `T extends F\u003cT>` form and it'd work with dependent contextual types...\n\n```ts\ndeclare const useQueries:\n \u003cT extends { [I in keyof T]: { key: unknown, fetch: (key: T[I][\"key\"]) => unknown, select: (data: ReturnType\u003cT[I][\"fetch\"]>) => unknown } }>\n (queries: T) =>\n { [I in keyof T]: ReturnType\u003cT[I][\"select\"]> }}\n\nconst results = useQueries([\n {\n key: \"0\",\n fetch: key => +key,\n select: data => [data] \n },\n {\n key: 1,\n fetch: key => key.toString(),\n select: data => ({ data })\n }\n])\n```\n\nA popular user of this m times n generics use case is [tanstack query](https://github.com/TanStack/query). Their `useQueries` looks like the `useQueries` above and is completely untyped.\n\n3. Inferring self referencing generics\n\nToday we again already do a good job of inferring `T extends F\u003cT>` types which are useful when typing any self referencing generics which occur in eDSLs example...\n\n```ts\ndeclare const createMachine:\n \u003cT extends StateNode\u003cT>>(definition: T) => \"STUB\"\n\ntype StateNode\u003cT> = {\n initial?: keyof T[\"states\" & keyof T],\n states?: {\n [K in keyof T[\"states\" & keyof T]]: StateNode\u003cT[\"states\" & keyof T][K]>\n }\n}\n\ncreateMachine({\n initial: \"a\", // can only be \"a\" or \"b\"\n states: {\n a: {\n initial: \"a1\", // can only be \"a1\" or \"a2\" or \"a3\"\n states: {\n a1: {},\n a2: {},\n a3: {}\n }\n },\n b: {}\n }\n})\n```\n\nBut you can't have functions in them as their parameters don't get inferred...\n\n```ts\ndeclare const createMachine:\n \u003cT extends StateNode\u003cT, T[\"context\"]> & { context: object }>(definition: T) => \"STUB\"\n\ntype StateNode\u003cT, C> = {\n initial?: keyof T[\"states\" & keyof T],\n states?: {\n [K in keyof T[\"states\" & keyof T]]: StateNode\u003cT[\"states\" & keyof T][K], C>\n },\n entry?: (context: C) => void\n}\n\ncreateMachine({\n initial: \"a\",\n context: { hello: \"world\" },\n states: {\n a: {\n initial: \"a1\",\n states: {\n a1: {},\n a2: {},\n a3: {}\n },\n entry: (context) => { // context is `object` instead of `{ hello: string }`\n console.log(\"entered node a\")\n }\n },\n b: {}\n }\n})\n```\n\nThis again is fixed by dependent contextual inference.\n\nA popular user that will get benefitted by this is [xstate](https://github.com/statelyai/xstate). In fact xstate is the main motivation for this feature request, even in a langauge as powerful as typescript there is no smart type-safe state machine abstraction out there.\n\n4. Many more use cases\n\nBecause `T extends F\u003cT>` are what I call \"self-type-checking types\" they are already very powerful and any inference problem can be refactored to it. So I think there are many many open issues that can be fixed by this... The only missing piece is that they don't work as expected when the expression is context-sensitive ie if it has functions in it... And hopefully we can fill that gap.\n\nThanks for reading!\n\nPS: Linking some issues this will indirectly fix...\n- #49618\n- #51377\n- #40439\n- #51612\n- #52047\n- perhaps many more I'll update as I find them","author":{"url":"https://github.com/devanshj","@type":"Person","name":"devanshj"},"datePublished":"2026-08-29T13:28:53Z","url":"https://github.com/microsoft/TypeScript/issues/64091"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:55e2db0f-e0b3-7a94-2473-5dcb4a0581f1 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 90DA:3F8AB1:BE46B8:F57C31:6B00EA55 |
| html-safe-nonce | 278975488b8c5d63e47977461aaba72714e48b61d0d26fde0cc2a9482db48429 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MERBOjNGOEFCMTpCRTQ2Qjg6RjU3QzMxOjZCMDBFQTU1IiwidmlzaXRvcl9pZCI6IjIzMTczNDg4OTc2ODI0MTgyNjEiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 84bd9a506fd550921a79b1cf46c6b92d70bf0d2172826481e41380c6fcd9caf9 |
| hovercard-subject-tag | issue:5286787810 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/64091/issue_layout |
| twitter:image | https://opengraph.githubassets.com/a0f62c1e1f5d19c5ba3ee7cc2b7a21b2ca7573e59b671fe44bc9ed9746298311/microsoft/TypeScript/issues/64091 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/a0f62c1e1f5d19c5ba3ee7cc2b7a21b2ca7573e59b671fe44bc9ed9746298311/microsoft/TypeScript/issues/64091 |
| og:image:alt | 🔍 Search Terms Dependent contextual inference, self type checking types, can't infer type parameters from context-sensitive expressions, self referencing types ✅ Viability Checklist This wouldn't b... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | devanshj |
| hostname | github.com |
| expected-hostname | github.com |
| None | 4ef498cbabcbe3c50befc7a5b743e7072ee770b4daf0e15e54801180d1fa91fc |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9983dd5da06943f833c971dd5b6bc988e2858be5 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width