microsoft / microsoft/TypeScript
Suggestion: optional globals
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
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):
windowwill only exist during the client runtimetypeof window !== undefined ? window.alert('yay') : undefined;globalandrequirewill only exist during the server runtimetypeof 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.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Empieza leyendo el issue relacionado #21965 y los ejemplos de optional-global de este issue; no se indica ningún archivo fuente ni punto de entrada de pruebas. Para completar el trabajo sería necesario acordar un diseño en el que los globales posiblemente no declarados necesiten una guarda typeof, preservando al mismo tiempo el comportamiento existente en tiempo de ejecución, junto con las pruebas correspondientes del compilador.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- javascript, typescript
- Área
- compilers
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 25/100