microsoft / microsoft/TypeScript

Static variable may be undefined when constructing an object of the same class

Abierto
#43,285 1 comentario 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Bug Report

I'm not sure whether this may be a issue that can be fixed or just keep it as is "by design". I haven't found any other issues similar to this one here, at least with the search terms I tried (sorry if someone else already reported this 🙂).

🔎 Search Terms

static, undefined, uninitialized, constructor

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about static variables, variable order initialization, etc., but none of them seem to match this.

At the moment of writing this, TypeScript version is 4.2.3.

⏯ Playground Link

Playground Link

💻 Code
class A {
    public static readonly instance: A = new A();
    public static readonly constant: number = 1;
    
    public constructor() {
        console.log(A.constant, A.constant * 5);
        console.log(A.constant.toString());
    }
}
🙁 Actual behavior

When calling the constructor to initialize the static variable instance, A.constant is not yet initialized (it's undefined), so the constructor logs undefined, NaN.

In addition, A.constant.toString() gives a javascript execution error, which even in strict mode the compiler doesn't catch.

🙂 Expected behavior

The compiler could tell that constant has type number | undefined at that moment (manually changing the type of constantto number | undefined correctly yields a compiler error) or even rearrange the generated javascript to initialize first constant and then instance (which I think it may be more difficult in more complex scenarios).

Thank you very much!

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con la reproducción vinculada en TypeScript Playground y compara el JavaScript emitido con el orden de inicialización indicado. Traza cómo gestiona el comprobador de tipos la inicialización de propiedades estáticas durante la construcción y determina después si la finalización debería ser un diagnóstico, un cambio en la emisión o una decisión de diseño explícita; verifica el resultado con un caso de regresión.

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
Error
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.