Title: When resolving incompatible signatures, skip callbacks with `never` arguments [ts(2349)] · Issue #42487 · microsoft/TypeScript · GitHub
Open Graph Title: When resolving incompatible signatures, skip callbacks with `never` arguments [ts(2349)] · Issue #42487 · microsoft/TypeScript
X Title: When resolving incompatible signatures, skip callbacks with `never` arguments [ts(2349)] · Issue #42487 · microsoft/TypeScript
Description: Suggestion TypeScript sometimes infers empty arrays as having type never[]. Usually, this doesn't cause problems, until it gets unioned with another type, and you try to call it as a function/method: function orDefault
Open Graph Description: Suggestion TypeScript sometimes infers empty arrays as having type never[]. Usually, this doesn't cause problems, until it gets unioned with another type, and you try to call it as a function/metho...
X Description: Suggestion TypeScript sometimes infers empty arrays as having type never[]. Usually, this doesn't cause problems, until it gets unioned with another type, and you try to call it as a function/m...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/42487
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"When resolving incompatible signatures, skip callbacks with `never` arguments [ts(2349)]","articleBody":"# Suggestion\r\n\r\nTypeScript sometimes infers empty arrays as having type `never[]`. Usually, this doesn't cause problems, until it gets unioned with another type, and you try to call it as a function/method:\r\n\r\n```ts\r\nfunction orDefault\u003cT, D>(x: T | null, d: D): T | D {\r\n if (x === null) {\r\n return d;\r\n }\r\n return x;\r\n}\r\n\r\nconst xs: string[] | null = [\"a\", \"bc\", \"def\"];\r\n\r\n// y: string[] | never[]\r\nconst y = orDefault(xs, []);\r\n\r\n// ERR: This expression is not callable.\r\n// Each member of the union type \r\n// (\u003cU>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[])\r\n// | (\u003cU>(callbackfn: (value: never, index: number, array: never[]) => U, thisArg?: any) => U[])\r\n// has signatures, but none of those signatures are compatible with each other. (2349)\r\nconst yThen = y.map(item => item.length);\r\nconst yChain = orDefault(xs, []).map(item => item.length);\r\n```\r\n\r\nIn this example, since the `[]` is typed as `never[]`, the `.map` method has a union type with two incompatible types; one possibility is a `string`, `number`, `string[]` argument list returning a generic `U`, and the other is a `never`, `number`, `never[]` argument list returning a generic `U`.\r\n\r\nRight now, tsc doesn't distinguish between the two; since they're incompatible, it raises `ts(2349)`. This can make it difficult to write nicely-chainable union values, since the inferred values for \"empty\" or \"impossible\" variants prevent type inference from working.\r\n\r\n\r\nHowever, there's a very easy reason to see why the first overload should be preferred: **values of type `never` shouldn't exist, so a function asking for a `never` will never be called**.\r\n\r\nWhile applying this rule in general is too extreme (since it would likely open up many soundness holes), we can add a small exception to `ts(2349)`: before rejecting the call for having incompatible callback types, check to see if any argument is a callback expecting `never` as any argument. If so, replace that callback with the most-general function type, `(...args: unknown[]) => never`. Then attempt to type-check with this type.\r\n\r\nWe can see that the existing type machinery can handle the code after this \"fix\":\r\n\r\n```ts\r\nconst func: (\u003cU>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[])\r\n | ((...args: unknown[]) => never)\r\n = null as any;\r\n\r\n// item: string\r\n// res: number[]\r\nconst res = func(item => item.length);\r\n```\r\n\r\nThis change is very narrow, since it only applies to code that:\r\n- is currently rejected by `ts(2349)`\r\n- AND one of the union signature's parameters is a callback \r\n- AND that callback has an argument with type `never`\r\n\r\nIn particular, since it only affects code that today fails to compile, it can't introduce new breaking changes.\r\n\r\nDespite being fairly narrow, it should help out inference for many common functions, especially related to empty arrays and other empty collections, including `.map`, `.filter`, `.flatMap`, `.reduce`, etc.\r\n\r\n## 🔍 Search Terms\r\n\r\n- empty array map\r\n- \"This expression is not callable\"\r\n- Each member of the union type '(\u003cU>(callbackfn: (value: Item, index: number, array: Item[]) => U, thisArg?: any) => U[]) | (\u003cU>(callbackfn: (value: never, index: number, array: never[]) => U, thisArg?: any) => U[])' has signatures, but none of those signatures are compatible with each other\r\n- ts(2349)\r\n- never type \r\n- incompatible callbacks\r\n\r\nVaguely related, but broader/different from this proposal: #40157\r\n\r\n- specific issue with empty tuples: #38514\r\n- more elaborate related case for ts(2349) not specific to arrays/`never` #38048\r\n\r\n\r\nList of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.\r\n\r\n## ✅ Viability Checklist\r\n\r\n\u003c!--\r\n Suggestions that don't meet all these criteria are very, very unlikely to be accepted.\r\n We always recommend reviewing the TypeScript design goals before investing time writing\r\n a proposal for ideas outside the scope of the project.\r\n-->\r\nMy suggestion meets these guidelines:\r\n\r\n* [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code\r\n* [x] This wouldn't change the runtime behavior of existing JavaScript code\r\n* [x] This could be implemented without emitting different JS based on the types of the expressions\r\n* [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)\r\n* [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).\r\n\r\n\r\n\r\n\r\n## 📃 Motivating Example\r\n\r\n```ts\r\nfunction orDefault\u003cT, D>(x: T | null, d: D): T | D {\r\n if (x === null) {\r\n return d;\r\n }\r\n return x;\r\n}\r\n\r\nconst xs: string[] | null = [\"a\", \"bc\", \"def\"];\r\n// does not type-check today, due to ts(2349)\r\nconst fixed: number[] = orDefault(xs, []).map(item => item.length);\r\n```\r\n\r\n## 💻 Use Cases\r\n\r\nMaking \"chaining\" libraries more ergonomic, especially when dealing with results.\r\n\r\nImproves types for various array methods.\r\n\r\nAlso applies to other collections, like `new Set([])` having type `Set\u003cnever>`; this makes `.forEach` callable on a union value with `new Set([])` as one possible alternative.\r\n\r\n","author":{"url":"https://github.com/Nathan-Fenner","@type":"Person","name":"Nathan-Fenner"},"datePublished":"2021-01-26T00:48:15Z","url":"https://github.com/microsoft/TypeScript/issues/42487"}
| 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:dffd2334-5c5d-e422-8c15-5c8b41e96e11 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A2F8:14F601:B81FB2:ED60F6:6B00E798 |
| html-safe-nonce | 69c4fe265aeef749c80f1c2e9454c0c36b809297f727169c5df7b1694e235d37 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMkY4OjE0RjYwMTpCODFGQjI6RUQ2MEY2OjZCMDBFNzk4IiwidmlzaXRvcl9pZCI6Ijc0NDEwMjU3NTY4NzM5NDI5MzYiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 871eb88a7e345c17c921d8ff32b7dab432231212e4901bed079e6d914d49fa0c |
| hovercard-subject-tag | issue:793831282 |
| 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/42487/issue_layout |
| twitter:image | https://opengraph.githubassets.com/820bf291ff71d40497671d31f30eebef36c6862a8fd4025107cb433f5358fb6c/microsoft/TypeScript/issues/42487 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/820bf291ff71d40497671d31f30eebef36c6862a8fd4025107cb433f5358fb6c/microsoft/TypeScript/issues/42487 |
| og:image:alt | Suggestion TypeScript sometimes infers empty arrays as having type never[]. Usually, this doesn't cause problems, until it gets unioned with another type, and you try to call it as a function/metho... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Nathan-Fenner |
| hostname | github.com |
| expected-hostname | github.com |
| None | 27088b6977484d0d3321d9a11c907c6d6637b315cfa359ef7952dbf6292f9b14 |
| 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 | 624179fb8b88d26ba5bba08894eb60a1c5a1d93d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width