Title: Infer-only function generics · Issue #62182 · microsoft/TypeScript · GitHub
Open Graph Title: Infer-only function generics · Issue #62182 · microsoft/TypeScript
X Title: Infer-only function generics · Issue #62182 · microsoft/TypeScript
Description: 🔍 Search Terms generic infer generic typeof typeof arguments infer-only generics infer arguments unoverridable generics ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change ...
Open Graph Description: 🔍 Search Terms generic infer generic typeof typeof arguments infer-only generics infer arguments unoverridable generics ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScri...
X Description: 🔍 Search Terms generic infer generic typeof typeof arguments infer-only generics infer arguments unoverridable generics ✅ Viability Checklist This wouldn't be a breaking change in existing Type...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/62182
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Infer-only function generics","articleBody":"### 🔍 Search Terms\n\n* `generic infer`\n* `generic typeof`\n* `typeof arguments`\n* `infer-only generics`\n* `infer arguments`\n* `unoverridable generics`\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\nAlthough there are many proposals for various syntax to allow specifying only specific, named generics (e.g. #23696) or skipping specification of certain generics (e.g. #26242), these miss a key use case: **sometimes you want to reference an inferred type that doesn't make sense to override**.\n\nI propose adding a way to reference inferred types in generics, without making them able to be manually overridden, by using the `infer` keyword in function argument type definitions.\n\n```typescript\nfunction create\u003c\n TOutput = InferOutput\u003cTTableName>,\n TInput = InferInput\u003cTTableName>,\n>(\n table: infer TTableName extends string,\n data?: TInput\n): Promise\u003cTOutput>\n```\n\nTheoretically, this could also be applied to classes:\n\n```typescript\nclass DatabaseTable {\n constructor(public readonly name: infer TTableName extends string) {}\n\n create\u003cTInput = InferInput\u003cTTableName>, TOutput = InferOutput\u003cTTableName>>(input: TInput): TOutput {}\n}\n```\n\nBut I'll admit that I haven't thought super deeply about the use cases or implications of that, so I'm going to focus on the function use case.\n\n### 📃 Motivating Example\n\nConsider the following generic function that automatically infers the input and output types of a SQL `CREATE` query based on the provided table name:\n\n```typescript\nasync function create\u003c\n TTableName extends string,\n TOutput = InferOutput\u003cTTableName>,\n TInput = InferInput\u003cTTableName>,\n>(\n table: TTableName,\n data?: TInput\n): Promise\u003cTOutput> {\n // stub\n return {} as unknown as TOutput\n}\n```\n\nThis works as is, but it does come with a few limitations.\n\n### Limitations\n\n#### Redundant and/or Contradictory `TTableName` definitions\n\nIdeally, we want to be able to override `TOutput` and `TInput` for special cases, but overriding `TTableName` doesn't really make sense. However, we are currently _forced_ to manually specify `TTableName` because it is a required generic parameter:\n\n```typescript\n// this works, but is frustratingly redundant\ncreate\u003c'users', UserOut, UserIn>('users', {})\n```\n\nIt also leads to potentially confusing contradictions in the types,\n\n```typescript\n// Argument of type '\"friends\"' is not assignable to parameter of type '\"users\"'. ts(2345)\ncreate\u003c'users', UserOut, UserIn>('admins', {})\n```\n\n#### Inability to define a default value\n\nBecause `TTableName` is a standard generic that can be overridden, we can't define a default value for `table` in the function definition -- after all, the caller _could_ have specified a value for `TTableName`, and our default value might not agree with it!\n\n```typescript\ncreate\u003c...>(\n // Type 'string' is not assignable to type 'TTableName'.\n // 'string' is assignable to the constraint of type 'TTableName', but 'TTableName' could be instantiated with a different subtype of constraint 'string'. ts(2322)\n table: TTableName = 'users',\n data?: TInput\n)\n```\n\n### The Solution\n\nWhat we really want is a way to reference the inferred type of `table` _without_ having to define a redundant, potentially conflicting, overridable generic. This could be accomplished by allowing the `infer` keyword to be used as the type of a function argument:\n\n```typescript\nfunction create\u003c\n TOutput = InferOutput\u003cTTableName>,\n TInput = InferInput\u003cTTableName>,\n>(\n table: infer TTableName extends string,\n data?: TInput\n): Promise\u003cTOutput>\n```\n\nThis would expose the type `TTableName` in all of the same contexts that other generics could be used:\n\n* In other generics\n* In the return type\n* in subsequent arguments\n* In the function body\n\n#### Implementation challenges\n\n> _\"You know nothing, Jon Snow\"_ - Ygritte\n\nI freely admit that my knowledge of TypeScript internals is, even generously... sparse. That said, I do have some thoughts about the potential challenges of implementing this feature.\n\nFirst of all, it seems that these \"named inferred argument types\" (for lack of a better term) would most likely need to be processed _before everything else_ to allow them to be referenced everywhere, including in the (ostensibly preceding) generics. I'm not sure how feasible that is, or if the TypeScript parser would easily handle something like that.\n\n### 💻 Use Cases\n\n### What do you want to use this for?\n\nThis would be invaluable for library development in a plethora of use cases. Personally, I tend to develop custom database wrappers and query builders, every single one of which has suffered some of the limitations of the current syntax.\n\n### What shortcomings exist with current approaches?\n\n* Redundancy when you must manually specify generics which are normally inferred\n* Potentially confusing contradictions between the generics and actual arguments\n* Inability to specify default values for inferred generics\n\n### What workarounds are you using in the meantime?\n\nIn the meantime, I am sucking it up and just having the redundancy and being diligent about conflicting types. For the default values problem, there are some possible workarounds, such as defining the default in the function body:\n\n```typescript\nasync function create\u003c\n TTableName extends string = 'users',\n TOutput = InferOutput\u003cTTableName>,\n TInput = InferInput\u003cTTableName>,\n>(\n table?: TTableName,\n data?: TInput\n): Promise\u003cTOutput> {\n const actualTable = table || 'users'\n // stub\n return {} as unknown as TOutput\n}\n```\n\nThis technically works, but comes with its own limitations.","author":{"url":"https://github.com/rintaun","@type":"Person","name":"rintaun"},"datePublished":"2025-08-03T08:58:26Z","url":"https://github.com/microsoft/TypeScript/issues/62182"}
| 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:116b89ca-136f-d7f7-0667-f3d91286d223 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8FF4:76F02:338BF09:41F2096:6B01D8C5 |
| html-safe-nonce | fd244048beb7426633366cb020c2bf2f96f219347fce897264be68da7d9a1cb3 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4RkY0Ojc2RjAyOjMzOEJGMDk6NDFGMjA5Njo2QjAxRDhDNSIsInZpc2l0b3JfaWQiOiI2Njc5NDM2OTYzMzMxODIzODEzIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | fc9db3e8301cfd3fa2c3e601772e3464e9506ada706813d3e79a24f1358c19e6 |
| hovercard-subject-tag | issue:3286970301 |
| 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/62182/issue_layout |
| twitter:image | https://opengraph.githubassets.com/640381ef8418be43187dc6fc1d047a02ac79bd38210406d84b5aa3e96ad3ad63/microsoft/TypeScript/issues/62182 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/640381ef8418be43187dc6fc1d047a02ac79bd38210406d84b5aa3e96ad3ad63/microsoft/TypeScript/issues/62182 |
| og:image:alt | 🔍 Search Terms generic infer generic typeof typeof arguments infer-only generics infer arguments unoverridable generics ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScri... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | rintaun |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| 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 | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width