René's URL Explorer Experiment


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

direct link

Domain: github.com

IPv4 address: 140.82.114.3


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:b7a4ac00-ab41-7ab8-d443-52c6b66e48ad
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id8456:29CA94:67277A:8E2635:6B0477D0
html-safe-nonce833f1c2280ab6ca616be98d355ac497ba03d6ba98842cebd15e41b6d1d8b58de
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4NDU2OjI5Q0E5NDo2NzI3N0E6OEUyNjM1OjZCMDQ3N0QwIiwidmlzaXRvcl9pZCI6Ijg4ODk1OTYxOTYxODMzODc2OCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac97074f7f88d6a547d4f3d79cfe4132abf86824635fcdf1835e7faffae39aa45d
hovercard-subject-tagissue:2470772222
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/59657/issue_layout
twitter:imagehttps://opengraph.githubassets.com/e60e50711b0a3398aad2e6213dde984dec7cb9f6e4c526342f309267fbae805c/microsoft/TypeScript/issues/59657
twitter:cardsummary_large_image
og:imagehttps://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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamenekolab
hostnamegithub.com
expected-hostnamegithub.com
None9c099f1b85def81ca352464c276510dfef32deaf3c305404e65b8d270284a58b
turbo-cache-controlno-preview
go-importgithub.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git
octolytics-dimension-user_id6154722
octolytics-dimension-user_loginmicrosoft
octolytics-dimension-repository_id20929025
octolytics-dimension-repository_nwomicrosoft/TypeScript
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id20929025
octolytics-dimension-repository_network_root_nwomicrosoft/TypeScript
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasecf73f57448d52b3a7b619195e182b33d3b3454ca
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/microsoft/TypeScript/issues/59657#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F59657
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmicrosoft%2FTypeScript%2Fissues%2F59657
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=microsoft%2FTypeScript
Reloadhttps://github.com/microsoft/TypeScript/issues/59657
Reloadhttps://github.com/microsoft/TypeScript/issues/59657
Reloadhttps://github.com/microsoft/TypeScript/issues/59657
microsofthttps://github.com/microsoft
TypeScripthttps://github.com/microsoft/TypeScript
Codehttps://github.com/microsoft/TypeScript
Issues5k (5k)https://github.com/microsoft/TypeScript/issues
Pull requests320 (320)https://github.com/microsoft/TypeScript/pulls
Actionshttps://github.com/microsoft/TypeScript/actions
Projectshttps://github.com/microsoft/TypeScript/projects
Wikihttps://github.com/microsoft/TypeScript/wiki
Security and qualityhttps://github.com/microsoft/TypeScript/security
Insightshttps://github.com/microsoft/TypeScript/insights
https://github.com/microsoft/TypeScript
New issuehttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/59657
New issuehttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/59657
Make type narrowing for destructured discriminated unions work for more typeshttps://github.com/microsoft/TypeScript/issues/59657#top
Domain: check: Control FlowThe issue relates to control flow analysishttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Domain%3A%20check%3A%20Control%20Flow%22
Possible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some caseshttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Possible%20Improvement%22
Backloghttps://github.com/microsoft/TypeScript/milestone/29
https://github.com/nekolab
Yi S. (nekolab)https://github.com/nekolab
on Aug 16, 2024https://github.com/microsoft/TypeScript/issues/59657#issue-2470772222
https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Typeshttps://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goalshttps://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
Vue Piniahttps://pinia.vuejs.org/
More detailed playground linkhttps://www.typescriptlang.org/play/#code/C4TwDgpgBAShBmAeAKgPigXigbygNwEMAbAVwgC4pkoBfAKDtEigBEDgC4CATETHOlCgAnCDxCU4SYMLKpBUMARBEA9j0kJEAZxkBLAHYBzefUbhobDgDlVwLr37YFo8ZqTxi2iPKFKV6tzuiAYkRESmDEyW7AT8VpxijgA+rLG29kkgDNwQAMZEBKJQeaoGulDcsZQJDKXlwDgiWQA0ispqPLT8VRwMevBQABSuvAB0hKQQAJQCfh2BE8RkQlAA9GtQiBg7UIbwEMKi3FAE2lAARLrChkZQqaHhF1AARiSN2gAWqmEnL9DXW50MzwEgGPLAPRlPbaBIOEBDIJpDjTSgnPTnOFZObNYAkYQGSpjUYgJZTYH9QZDDFY8SI2LTWbOIQkskrVbrTbbXb7Q7HU7nF6qVREMSEt4fb6-V7QGRkBT+TrcNnQIQbLY7LC8o4QE5nS6A4z3KCPIjPCVQL4-Ih-AH6YwUuig8GQ6FnbzCYC03iImoMyjuw7Ac7ozGxeE4MwDYasyZkJkKQOe70I3oEaYuLIqjmcjU8gwHHV685y6AAd0+ejynxhUAgAA9IBDda93ntgAByc4GIrCVRllsvPh2T6HdrAT4KhY8bNqrmavYFvkt-VXe13B5hM2tyXW22W9cUoA
Fix discriminant property check #29110https://github.com/microsoft/TypeScript/pull/29110
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
Help Wantedhttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Help%20Wanted%22
Possible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some caseshttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Possible%20Improvement%22
on Aug 16, 2024https://github.com/microsoft/TypeScript/issues/59657#event-13916754170
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
Backloghttps://github.com/microsoft/TypeScript/milestone/29
on Aug 16, 2024https://github.com/microsoft/TypeScript/issues/59657#event-13916754400
https://github.com/nekolab
Yi S. (nekolab)https://github.com/nekolab
on Aug 17, 2024https://github.com/microsoft/TypeScript/issues/59657#issuecomment-2294956023
https://github.com/microsoft/TypeScript/wiki/Reference-Checker-Inference#type-parameter-inferencehttps://github.com/microsoft/TypeScript/wiki/Reference-Checker-Inference#type-parameter-inference
Yi S. (nekolab)https://github.com/nekolab
on Aug 25, 2024https://github.com/microsoft/TypeScript/issues/59657#event-14003310122
Narrow destructured variables based on initializer's analysis resulthttps://github.com/nekolab/TypeScript/commit/77cb42b3d596543bb89a8c338e72bcc3aed52bd1
https://docs.github.com/articles/closing-issues-via-commit-messages
77cb42bhttps://github.com/nekolab/TypeScript/commit/77cb42b3d596543bb89a8c338e72bcc3aed52bd1
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
Domain: check: Control FlowThe issue relates to control flow analysishttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Domain%3A%20check%3A%20Control%20Flow%22
on Oct 16, 2025https://github.com/microsoft/TypeScript/issues/59657#event-20330972550
Ryan Cavanaugh (RyanCavanaugh)https://github.com/RyanCavanaugh
Help Wantedhttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Help%20Wanted%22
on Nov 10, 2026https://github.com/microsoft/TypeScript/issues/59657#event-35721516503
Sign up for freehttps://github.com/signup?return_to=https://github.com/microsoft/TypeScript/issues/59657
Sign in to commenthttps://github.com/login?return_to=https://github.com/microsoft/TypeScript/issues/59657
Domain: check: Control FlowThe issue relates to control flow analysishttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Domain%3A%20check%3A%20Control%20Flow%22
Possible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some caseshttps://github.com/microsoft/TypeScript/issues?q=state%3Aopen%20label%3A%22Possible%20Improvement%22
BacklogNo due datehttps://github.com/microsoft/TypeScript/milestone/29
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Response headers:
Servergithub.com
Content-Typetext/html; charset=utf-8
Cache-Controlmax-age=0, private, must-revalidate

Viewport: width=device-width


URLs of crawlers that visited me.