microsoft / microsoft/TypeScript

Suggestion: optional globals

Aperta
#36,057 6 commenti 18 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Awaiting More Feedback Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia leggendo l’issue correlata #21965 e gli esempi di optional-global in questa issue; non è indicato alcun file sorgente né alcun punto di ingresso dei test. Il completamento richiederebbe un design concordato in cui le variabili globali eventualmente non dichiarate debbano avere una guardia typeof, preservando al contempo il comportamento di runtime esistente, insieme ai corrispondenti test del compilatore.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
javascript, typescript
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.