microsoft / microsoft/TypeScript

Variables that are used-before-assigned are typed without `undefined`

Abierto
#53,306 2 comentarios 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

🔎 Search Terms

variable use before assign

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

Playground link with relevant code

💻 Code
let xx: number;

  xx.toFixed();
// ^?
// typeof xx === number ❌

let yy!: number;

  yy.toFixed();
// ^?
// typeof yy === number ✅
🙁 Actual behavior

TS reports the type of the used-before-assigned variable xx as number, and reports error Variable 'xx' is used before being assigned. (2454)

🙂 Expected behavior

TS reports the type of xx as number | undefined.

Additional info

This behaviour makes it difficult for us to write lint rules because when we attempt to check if the variable is undefined, the type system reports that it is not.

Examples:

  • checking for unnecessary conditions based on types
    • if (xx != null) {} The types say xx is number, so != null looks like it's unnecessary.
  • checking for unnecessary type assertions
    • xx! Again the types say xx is number, so the non-null assertion looks like it's unnecessary.

Example issue:

In the past we've manually coded up logic to do used-before-assigned checks where necessary - but it's pretty gnarly code to maintain and we have to ensure that we cover this case in our implementation.

It would be great if TS reported the "correct" type here with undefined.

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 el TypeScript Playground enlazado y reproduce la diferencia entre let xx: number y let yy!: number. Rastrea cómo el análisis del uso antes de la asignación afecta al tipo reportado y compara el manejo existente de typescript-eslint enlazado en el issue. Se considera terminado cuando la primera variable se muestra como number | undefined sin romper el diagnóstico ni el caso con aserción de no nulo.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Error
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.