Title: Proposal: optionally declared variables · Issue #23602 · microsoft/TypeScript · GitHub
Open Graph Title: Proposal: optionally declared variables · Issue #23602 · microsoft/TypeScript
X Title: Proposal: optionally declared variables · Issue #23602 · microsoft/TypeScript
Description: Scenario When writing code that will run in both Node.js and browser environments (e.g. a React component compatible with SSR), it's sometimes necessary that part of the code only executes in one environment and not the other. A few brow...
Open Graph Description: Scenario When writing code that will run in both Node.js and browser environments (e.g. a React component compatible with SSR), it's sometimes necessary that part of the code only executes in one e...
X Description: Scenario When writing code that will run in both Node.js and browser environments (e.g. a React component compatible with SSR), it's sometimes necessary that part of the code only executes in o...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/23602
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Proposal: optionally declared variables","articleBody":"# Scenario\r\n\r\nWhen writing code that will run in both Node.js and browser environments (e.g. a React component compatible with SSR), it's sometimes necessary that part of the code only executes in one environment and not the other.\r\n\r\nA few browser-only examples:\r\n\r\n- `document.querySelector()` to find an element in the DOM.\r\n- `document.title = \"new title\"` to update the page title.\r\n\r\nTo avoid executing these in Node.js, the following pattern is used:\r\n\r\n```ts\r\nif (typeof document !== \"undefined\") {\r\n // Safely use `document`.\r\n document.title = \"new title\";\r\n}\r\n```\r\n\r\nNow the developer needs to configure TypeScript to include the types for `document`. It basically boils down to them deciding whether or not to include `dom` in the `lib` compiler option. \r\n\r\n(`dom.d.ts` is distributed with TypeScript and includes:)\r\n\r\n```ts\r\ndeclare var document: Document;\r\n```\r\n\r\nUnfortunately both options have compromises:\r\n\r\n- **don't include it** and `document` won't be declared, and TypeScript will warn `Cannot find name 'document'.`\r\n- **do include it** and `document` will be declared as a `Document`, but not as `Document | undefined`, so [`strict-type-predicates`](https://palantir.github.io/tslint/rules/strict-type-predicates/) will complain that the check is unnecessary\r\n\r\nA motivated developer may choose to fork `dom.d.ts` and add `| undefined` to all of the global variable declarations, and satisfy `strict-type-predicates`.\r\n\r\nHowever one final piece of safety is still missing: ensuring `typeof document !== \"undefined\"` is used, rather than `document !== undefined`. At runtime if `document` (or any name) isn't declared, and is used outside `typeof`, a `ReferenceError` is thrown. For this reason it's necessary to always choose `typeof` when performing environment \"sniffing\".\r\n\r\nTypeScript currently cannot model \"optionally declared variables\", where a variable \"might\" be declared. Without this, TypeScript doesn't have enough information to warn about code that _may_ throw `ReferenceError`.\r\n\r\n# Proposal\r\n\r\nIntroduce new syntax and type system concepts to allow the \"optional declaration\" of variables. Emit would be unaffected.\r\n\r\n**Proposed syntax:**\r\n\r\n```ts\r\ndeclare? var window: Window;\r\n```\r\n\r\nThis is distinct from:\r\n\r\n```ts\r\ndeclare var window: Window | undefined;\r\n```\r\n\r\nIn the first case, it's describing that `window` may not be declared, and referencing `window` may throw a `ReferenceError`. In the second case, `window` is *always* declared, but might have the value `undefined`.\r\n\r\n**Implementation:**\r\n\r\n- The grammar would need to be extended to match `?` following `declare`.\r\n- The AST would need a representation (e.g. a flag for `DeclareKeyword` or a new `OptionalDeclareKeyword`).\r\n- The type system would need to track if a variable is optionally-declared, and support type-narrowing to a standard variable via `typeof` guards.\r\n- For this to actually be useful, the type checker should warn if \"optionally declared\" variables are referenced. \r\n- If a variable is \"optionally declared\", that information should be included in the string representation (e.g. `declare? var document: Document`), e.g. when hovering a name in VS Code.\r\n\r\n**Shortcomings:**\r\n\r\n- It would be convenient if a single `typeof window !== \"undefined\"` guard could safely grant access to other browser globals (e.g. `document`, `performance`, etc). This current proposal would require separate `typeof` checks for each global.","author":{"url":"https://github.com/bradleyayers","@type":"Person","name":"bradleyayers"},"datePublished":"2018-04-21T07:55:12Z","url":"https://github.com/microsoft/TypeScript/issues/23602"}
| 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:6fb3886c-6f57-ec10-89ca-191402583b47 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B320:2D2F2F:3084F99:3DE7B52:6B01BCC4 |
| html-safe-nonce | 2501bf19027b4870f361511ef62ec163b3100086b523999e4c6783407576c846 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCMzIwOjJEMkYyRjozMDg0Rjk5OjNERTdCNTI6NkIwMUJDQzQiLCJ2aXNpdG9yX2lkIjoiMjY1NTI5Njk0NzY2OTI4NjA4NCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 70fa6004c704bd3ce9f458cbb3ecf31560f4e45d116fcc8f466b13d6f0a01341 |
| hovercard-subject-tag | issue:316471560 |
| 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/23602/issue_layout |
| twitter:image | https://opengraph.githubassets.com/20a96d00fe8f23a3bcbdd8e0bf40d3af4ff6145138eec9685ec2e27113830aba/microsoft/TypeScript/issues/23602 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/20a96d00fe8f23a3bcbdd8e0bf40d3af4ff6145138eec9685ec2e27113830aba/microsoft/TypeScript/issues/23602 |
| og:image:alt | Scenario When writing code that will run in both Node.js and browser environments (e.g. a React component compatible with SSR), it's sometimes necessary that part of the code only executes in one e... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | bradleyayers |
| 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