question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Suggestion: optional globals

See original GitHub issue

Search Terms

Suggestion

Extracted from this related issue: https://github.com/microsoft/TypeScript/issues/21965

Currently TypeScript has no way to represent a global which may or may not exist at runtime.

For example, given a global called foo, we can only define it as:

declare global {
  const foo: number;
}

But what if foo does not always exist?

We can’t define it as T | undefined because this does not reflect the runtime behaviour. T | undefined means “this will be declared but its value might be undefined”, but the global may not be declared at all, in which case any references would result in ReferenceErrors at runtime.

declare global {
  const foo: number | undefined;
}
// TypeScript is happy for us to reference this. There's no compile error.
// The type is `number | undefined`.
// At runtime, if the global doesn't exist, we'll get a `ReferenceError` 😒
foo;

If there was a way to mark a global as optional, TypeScript would require a proper guard (typeof foo !== 'undefined') before it can be safely accessed. This way, TypeScript is alerting us to the possibilty of a runtime exception.

declare global {
  // example syntax
  const foo?: number;
}
// Compile error 😇
// Runtime exception 😇
foo;

if (typeof foo !== 'undefined') {
  // No compile error 😇
  // No runtime exception 😇
  // Type is `number`
  foo;
}

Use Cases

Examples of “optional globals” below.

In code that is shared between a client (browser) and server (Node):

  • window will only exist during the client runtime
    typeof window !== undefined ? window.alert('yay') : undefined;
    
  • global and require will only exist during the server runtime
    typeof process !== undefined ? process.env.FOO : undefined;
    

In code which may or may not be under test using Cypress, the global Cypress will only exist during runtime when the code is under test.

const getEnvVar = key => typeof Cypress !== 'undefined' ? Cypress.env(key) : process.env[key];

Examples

See above.

Checklist

My suggestion meets these guidelines:

  • This wouldn’t be a breaking change in existing TypeScript/JavaScript code
  • This wouldn’t change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript’s Design Goals.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:12
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
OliverJAshcommented, Sep 22, 2020

@mvasin What about the editor experience though? VS Code (for example) would need to choose which one of the TS configs to use. You might be able to compose multiple projects into one using project references, but then I’m still not sure the editor experience would be what we want, as outlined in an example above: https://github.com/microsoft/TypeScript/issues/36057#issuecomment-572582516. If I’m viewing a code file which is used in Node and in the browser, I should get an error if I try to use window/global, but as soon as I add a guard that error should disappear.

1reaction
OliverJAshcommented, Jan 9, 2020

Something else to consider: as well as marking individual globals as optional, we might also need a way to specify a group of globals as being optional.

In the example of code that is shared between client/server:

  • all globals inside of the dom lib must be optional (i.e. Window)
  • all globals inside of the @types/node types must be optional (i.e. NodeJS.Global)

Ideally, the implicit global type would work just like a tagged union:

Global = Window | NodeJS.Global

… and checking for the presence of properties in the union would narrow the implicit global type so that other properties can then be accessed without extra guards:

window; // Compile error 😇 
alert; // Compile error 😇 
addEventListener; // Compile error 😇 

if (type window !== 'undefined') {
  window; // No compile error 😇 

  // We checked for the existence of `window`, so other globals must also exist now
  alert('foo'); // No compile error 😇 
  addEventListener('load', () => {}); // No compile error 😇
}

In the meantime I’m simulating this by defining an alias:

type Env = typeof window | NodeJS.Global;

const hasWindow = typeof window !== 'undefined';

const env: Env = hasWindow ? window : global;

const checkIsEnvWindow = (_thisEnv: Env): _thisEnv is typeof window => hasWindow;

env.alert; // Compile error 😇
env.addEventListener; // Compile error 😇

if (checkIsEnvWindow(env)) {
  env.alert('foo'); // No compile error 😇
  env.addEventListener('load', () => {}); // No compile error 😇
}

The downside of this approach is that it relies on discipline—anyone can still reference/use the types for window and global.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Enable text suggestions in Windows - Microsoft Support
Use text suggestions to quickly complete words as you type a document, chat message, web form, or more.
Read more >
Suggesters | Elasticsearch Guide [8.5] | Elastic
Global suggest textedit. To avoid repetition of the suggest text, ... The suggest text is a required option that needs to be set...
Read more >
Is there a better way to do optional function parameters in ...
Here's an example for providing defaults for three optional arguments (with two required arguments) ... Just declare this function on the global escope....
Read more >
Globals // Statamic 3 Docs
Globals · Overview · Global Sets · Storage · Frontend Templating · Blueprints are Optional · Localization · Ideas on How to Use...
Read more >
Code completion | IntelliJ IDEA Documentation - JetBrains
For automatic completion enable the Show suggestions as you type option. Basic completion: Ctrl+Space. Smart type-matching completion: ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found