Title: Suggestion: control flow type analysis could account for reassignments through a closure · Issue #8353 · microsoft/TypeScript · GitHub
Open Graph Title: Suggestion: control flow type analysis could account for reassignments through a closure · Issue #8353 · microsoft/TypeScript
X Title: Suggestion: control flow type analysis could account for reassignments through a closure · Issue #8353 · microsoft/TypeScript
Description: TypeScript Version: 1.9.0-dev.20160427 Code: function iWantString(s: string) { if (typeof s !== "string") throw new TypeError("That is not a string!"); } declare let x: number | string | boolean; function func() { x = 1234; } if (typeof ...
Open Graph Description: TypeScript Version: 1.9.0-dev.20160427 Code: function iWantString(s: string) { if (typeof s !== "string") throw new TypeError("That is not a string!"); } declare let x: number | string | boolean; f...
X Description: TypeScript Version: 1.9.0-dev.20160427 Code: function iWantString(s: string) { if (typeof s !== "string") throw new TypeError("That is not a string!"); } declare let x: number |...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/8353
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Suggestion: control flow type analysis could account for reassignments through a closure","articleBody":"**TypeScript Version:** \n\n1.9.0-dev.20160427\n\n**Code:**\n\n``` ts\nfunction iWantString(s: string) {\n if (typeof s !== \"string\")\n throw new TypeError(\"That is not a string!\");\n}\n\ndeclare let x: number | string | boolean;\n\nfunction func() {\n x = 1234;\n}\n\nif (typeof x === \"string\") {\n func();\n iWantString(x);\n}\n```\n\n**Actual behavior:** \nThe call to `func()` doesn't influence the compiler's awareness on the possible types `x` might have after the call. It still thinks it is `string` and the call to `iWantString` fails at runtime.\n\n**Suggestion:**\nThe compiler could account for the possibility that `func` may reassign `x` as a captured variable, by storing a list of all the captured variables `func` may possibly reassign throughout its execution and the types they may hold at all return positions.\n\nFor the above example, the type of `x` would be widened to include the additional types `x` may receive during the execution of `func` (only `number` in this example). Right after the function returns, the type of `x` would be widened to `string | number` and `iWantString(x)` would fail at compile time.\n\n**Examples:**\n\n``` ts\ndeclare let x: boolean | number | string[] | number[];\n\nfunction func() {\n if (Math.random() > 0.5) {\n // Since 'x' has not been reassigned in this code path, there's no effect here\n return;\n }\n\n if (Math.random() > 0.5) {\n x = 4321; // no eventual effect\n x = true; // 'x' is added to the list with the possible type 'boolean'\n return;\n }\n\n x = 1234; // no eventual effect\n x = [\"a\", \"b\"]; // no eventual effect\n x = [1, 2]; // the entry for 'x' is extended to include type 'number[]'\n}\n\nif (typeof x === \"string\") {\n func();\n // type of x is widened to 'string | boolean | number[]'\n}\n```\n\nMore complex example that includes further calls within the called function itself to other functions that reassign `x` as a captured variable:\n\n``` ts\ndeclare let x: boolean | number | string[] | number[];\n\nfunction func1() {\n x = 4321; // no eventual effect\n x = true; // 'x' is added to the list for 'func1' with the possible type 'boolean'\n}\n\nfunction func2() {\n x = 1111; // 'x' is added to the list for 'func2' with the possible type 'number'\n}\n\nfunction func3() {\n if (Math.random() > 0.5) {\n func1(); // The list generated for 'func2' is merged into the one for 'func3'\n return;\n }\n else {\n func2(); // no eventual effect\n x = [2, 3]; // the entry for 'x' is extended to include type 'number[]' \n return;\n }\n\n x = 1234; // no eventual effect\n x = [\"a\", \"b\"]; // no eventual effect\n x = [1, 2]; // the entry for 'x' is extended to include type 'number[]'\n}\n\nif (typeof x === \"string\") {\n func3();\n // type of 'x' is widened to 'string | boolean | number[]'\n}\n```\n\n**Implementation details:**\n\nThis may look very complicated, but it isn't really compared to what has already been achieved for flow and assignment analysis (which is remarkable!). Here's one way to do it:\n\nFor any given function:\n1. Keep a list of all captured variables that are possibly reassigned in it.\n2. For every code path where one of these variables has been possibly reassigned, accumulate the possible types it may hold right before the function returns. Annotate these types on the list.\n3. A variable that is indirectly reassigned through a call to a secondary function is also considered a reassignment done by the calling function and will be included in the list.\n\nAfter each call to a function:\n1. Lookup the current set of scoped variables (including captured, closure-bound ones).\n2. Query each one of them in the list generated for the function that has just returned and merge the possible set of types specified in the list into the set of currently known ones. \n\nThat's it, nested calls naturally propagate this information backwards as this process is internally applied for them.\n\n(I have considered whether the set specified in list should entirely replace the current one, instead of just being merged. However, there is no guarantee here that in _all_ return positions the function has actually reassigned a particular variable. There's just the _possibility_ it did, unless slightly more advanced analysis is performed to detect when a particular variable is known for certain to have been reassigned in _every_ return path, and then the set can possibly be replaced).\n\n**Limitations:**\n\nFunctions that are called using `.call` or `.apply` or a more complex mechanism, like a `promise`, cannot be easily taken into account. However, I felt that the return for this enhancement is sufficient to justify the reasonable effort needed (on a personal note - I have no capability or time to implement something like this myself - the learning curve itself is very, very steep - but I might have tried if I could).\n\n_Edits `11 May 2016`: improved some phrasing corrected the terminology to 'reassignments` instead of 'mutations', and 'captured variables' instead of 'variables assigned through a closure'._\n","author":{"url":"https://github.com/malibuzios","@type":"Person","name":"malibuzios"},"datePublished":"2016-04-28T15:15:45Z","url":"https://github.com/microsoft/TypeScript/issues/8353"}
| 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:07e37110-bd18-f6c8-613f-b5c5d99fe3ef |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 95CE:364B55:8F02FF:BB1D6E:6B00DD6D |
| html-safe-nonce | db66ce9c81ab5fc0088d46ce6dbf42fc5f5a2ca68f93f03692cc6bbcaf21abc2 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5NUNFOjM2NEI1NTo4RjAyRkY6QkIxRDZFOjZCMDBERDZEIiwidmlzaXRvcl9pZCI6IjUzMjgxMTEyMDk3MTc3NTExNDkiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 00e6f7d32178d357b802ba1d8efb4e32eb9b925a903ce2af2df0f6d6b1f6f2aa |
| hovercard-subject-tag | issue:151669133 |
| 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/8353/issue_layout |
| twitter:image | https://opengraph.githubassets.com/168c03a2c0c0b3fdf7eeb59c8748e99169c50ebb79773391d16861be90ed09c5/microsoft/TypeScript/issues/8353 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/168c03a2c0c0b3fdf7eeb59c8748e99169c50ebb79773391d16861be90ed09c5/microsoft/TypeScript/issues/8353 |
| og:image:alt | TypeScript Version: 1.9.0-dev.20160427 Code: function iWantString(s: string) { if (typeof s !== "string") throw new TypeError("That is not a string!"); } declare let x: number | string | boolean; f... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | malibuzios |
| hostname | github.com |
| expected-hostname | github.com |
| None | 043c3f30fbcbe2c6c8e729e10cbbbc90c406546f9fbbb67c648d38f6b7d16daf |
| 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 | 5425dc24e8bd8d6fca9641a12afc984825a43875 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width