Title: Make type narrowing for destructured discriminated unions work for more types · Issue #59657 · microsoft/TypeScript · GitHub
Open Graph Title: Make type narrowing for destructured discriminated unions work for more types · Issue #59657 · microsoft/TypeScript
X Title: Make type narrowing for destructured discriminated unions work for more types · Issue #59657 · microsoft/TypeScript
Description: 🔍 Search Terms discriminant union, ref, control flow guard, type narrowing ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the runtime behavior of existing JavaScript c...
Open Graph Description: 🔍 Search Terms discriminant union, ref, control flow guard, type narrowing ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the r...
X Description: 🔍 Search Terms discriminant union, ref, control flow guard, type narrowing ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't chan...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/59657
X: @github
Domain: github.com
IPv4 address: 140.82.114.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Make type narrowing for destructured discriminated unions work for more types","articleBody":"### 🔍 Search Terms\r\n\r\ndiscriminant union, ref, control flow guard, type narrowing\r\n\r\n### ✅ Viability Checklist\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 isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types\r\n- [X] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals\r\n\r\n### ⭐ Suggestion\r\n\r\n```typescript\r\ntype Ref\u003cT> = { value: T }\r\ntype Data =\r\n | { ready: Ref\u003ctrue>, payload: string }\r\n | { ready: Ref\u003cfalse>, payload: null }\r\n\r\ndeclare const data: Data\r\nconst { ready, payload } = data\r\n\r\nif (ready.value) {\r\n payload // \u003c== currently inferred as \"string | null\" but should be \"string\"\r\n}\r\n```\r\n\r\nTreat types like `Ref\u003cT>` as a discriminant property in a union or find a way to narrow the type of `payload`\r\n\r\n### 📃 Motivating Example\r\n\r\nThis is a very common use case in the [Vue Pinia](https://pinia.vuejs.org/) state store library, millions of projects use this library and have code like\r\n```typescript\r\nconst store = useDataStore()\r\nconst { ready, payload } = storeToRefs(store)\r\n```\r\nIf we can improve this type narrowing behavior, the narrowed `payload` type can helps developer write safer code than before\r\n```typescript\r\n// before, Non-null assertion everywhere\r\nif (ready.value) {\r\n payload.xxxx() // \u003c=== false alert raised by typescript and developers have to use ?. or ! to avoid it\r\n payload?.xxxx() // \u003c=== ?. is unnecessary, generates dead code and brings cognitive confusion\r\n xxxxx(payload!)\r\n}\r\nxxxxx(payload!) // \u003c=== copied from the if block and forget to remove the ! mark, cannot receive alert from typescript\r\n\r\n// after, everything works fine\r\nif (ready.value) {\r\n payload.xxxx()\r\n xxxxx(payload)\r\n}\r\nxxxxx(payload) // received the null check protection from typescript\r\n```\r\n\r\n\r\n### 💻 Use Cases\r\n\r\n[More detailed playground link](https://www.typescriptlang.org/play/?#code/C4TwDgpgBAShBmAeAKgPigXigbygNwEMAbAVwgC4pkoBfAKDtEigBEDgC4CATETHOlCgAnCDxCU4SYMLKpBUMARBEA9j0kJEAZxkBLAHYBzefUbhobDgDlVwLr37YFo8ZqTxi2iPKFKV6tzuiAYkRESmDEyW7AT8VpxijgA+rLG29kkgDNwQAMZEBKJQeaoGulDcsZQJDKXlwDgiWQA0ispqPLT8VRwMevBQABSuvAB0hKQQAJQCfh2BE8RkQlAA9GtQiBg7UIbwEMKi3FAE2lAARLrChkZQqaHhF1AARiSN2gAWqmEnL9DXW50MzwEgGPLAPRlPbaBIOEBDIJpDjTSgnPTnOFZObNYAkYQGSpjUYgJZTYH9QZDDFY8SI2LTWbOIQkskrVbrTbbXb7Q7HU7nF6qVREMSEt4fb6-V7QGRkBT+TrcNnQIQbLY7LC8o4QE5nS6A4z3KCPIjPCVQL4-Ih-AH6YwUuig8GQ6FnbzCYC03iImoMyjuw7Ac7ozGxeE4MwDYasyZkJkKQOe70I3oEaYuLIqjmcjU8gwHHV685y6AAd0+ejynxhUAgAA9IBDda93ntgAByc4GIrCVRllsvPh2T6HdrAT4KhY8bNqrmavYFvkt-VXe13B5hM2tyXW22W9cUoA)\r\n\r\nThe use cases is actually shown in the motivating example.\r\n\r\nI've dig into the `checker.ts` for some time and here's my findings\r\n1. `getDiscriminantPropertyAccess` cannot treat `ready` as a discriminant property now because it needs to check `CheckFlags.Discriminant` which implies `CheckFlags.HasLiteralType`. It's a pretty strict check and as its name describes, `Ref\u003cT>` has no chance to pass this check.\r\n2. I'm not sure is it possible for relaxing the discriminate requirements but it seems to be a bad idea after some search. #29110 is what I found but it's a really old PR so maybe time changes now\r\n3. If we cannot solve it by using discriminant property narrowing, as a newbie to the typescript project, I just tried to debug the checker and have another idea\r\n```typescript\r\ninterface Ref\u003cT> { value: T }\r\ntype ToRefs\u003cT> = { [K in keyof T]: Ref\u003cT[K]> }\r\nfunction toRefs\u003cT>(o: T): ToRefs\u003cT> {\r\n return {} as any\r\n}\r\n\r\ninterface DataPrepared {\r\n ready: true\r\n payload: string\r\n}\r\n\r\ninterface DataNotPrepared {\r\n ready: false\r\n payload: null\r\n}\r\n\r\ntype Data = DataPrepared | DataNotPrepared\r\n\r\ndeclare const data: Data\r\nconst { ready, payload } = toRefs(data)\r\n\r\nfunction isDataReady(d: Data): d is DataPrepared {\r\n return d.ready.value\r\n}\r\n\r\nif (isDataReady(data)) {\r\n ready.value // \u003c=== inferred as boolean but should be true\r\n payload.value // \u003c=== inferred as \"string | null\" but should be string\r\n}\r\n\r\nfunction assertDataReady(d: Data): asserts d is DataPrepared {}\r\n\r\nif (ready.value) {\r\n assertDataReady(data)\r\n ready.value // \u003c=== inferred as true which is expected but it's narrowed by other code path\r\n payload.value // \u003c=== inferred as \"string | null\" but should be string\r\n}\r\n```\r\nCan we use type predicates or assert function to add more information to `payload`'s flow list? If it's possible, maybe we can do following steps while examine the `payload`\r\n1. check `payload`'s symbol, if its declaration is a `BindingPattern`\r\n2. check the flow list for `payload`, if the narrowed `data` is the initializer of `payload`'s declaration\r\n3. narrow the `payload` based on the narrowed `data`\r\n4. maybe it's gibberish but hope it helps\r\n","author":{"url":"https://github.com/nekolab","@type":"Person","name":"nekolab"},"datePublished":"2024-08-16T18:38:32Z","url":"https://github.com/microsoft/TypeScript/issues/59657"}
| 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:b7a4ac00-ab41-7ab8-d443-52c6b66e48ad |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8456:29CA94:67277A:8E2635:6B0477D0 |
| html-safe-nonce | 833f1c2280ab6ca616be98d355ac497ba03d6ba98842cebd15e41b6d1d8b58de |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4NDU2OjI5Q0E5NDo2NzI3N0E6OEUyNjM1OjZCMDQ3N0QwIiwidmlzaXRvcl9pZCI6Ijg4ODk1OTYxOTYxODMzODc2OCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 97074f7f88d6a547d4f3d79cfe4132abf86824635fcdf1835e7faffae39aa45d |
| hovercard-subject-tag | issue:2470772222 |
| 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/59657/issue_layout |
| twitter:image | https://opengraph.githubassets.com/e60e50711b0a3398aad2e6213dde984dec7cb9f6e4c526342f309267fbae805c/microsoft/TypeScript/issues/59657 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/e60e50711b0a3398aad2e6213dde984dec7cb9f6e4c526342f309267fbae805c/microsoft/TypeScript/issues/59657 |
| og:image:alt | 🔍 Search Terms discriminant union, ref, control flow guard, type narrowing ✅ Viability Checklist This wouldn't be a breaking change in existing TypeScript/JavaScript code This wouldn't change the r... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | nekolab |
| hostname | github.com |
| expected-hostname | github.com |
| None | 9c099f1b85def81ca352464c276510dfef32deaf3c305404e65b8d270284a58b |
| 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 | cf73f57448d52b3a7b619195e182b33d3b3454ca |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width