microsoft / microsoft/TypeScript

Infer const-ness of local let bindings that aren't assigned to

Abierto
#39,251 9 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.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

Search Terms

let const infer assignment

Suggestion

In some cases, type narrowing for const bindings is more effective than for let bindings. Specifically, using such bindings from a function that closes over them will keep the narrowed type, which doesn't happen for let binding, presumably on the assumption that those might be mutated at any time.

This suggests to treat local let bindings that are never assigned to (which can be determined by a rather straightforward static check on the syntax tree) like const bindings for this purpose.

(Interestingly, something like this seems to already exist for function parameters.)

Use Cases

Though some people have adopted a coding style where locals are declared with const unless assigned to, there's also a good argument to be made that that is not a very good use of brain cycles and just using let for all locals is fine. This proposal would improve type inference for people using the let style.

Examples

function foo() {
  let v: number[] | null = Math.random() < 0.5 ? [1] : null
  if (Array.isArray(v)) setTimeout(() => console.log(v.length), 100)
}

The compiler complains that v is possibly null. If the binding is changed to const the problem goes away. If v is made a function parameter it also doesn't occur. (But comes back when a v = null statement is added, suggesting a check like the one suggested here is being done in that case.)

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

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 ejemplo foo proporcionado y compara el comportamiento local-let propuesto con el comportamiento existente para las vinculaciones const y los parámetros de función. Define la finalización como conservar el tipo estrechado dentro del callback de cierre cuando una vinculación let local no tiene asignaciones, manteniendo el comportamiento existente cuando puede mutarse; añade cobertura para ambos casos.

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

Evaluación

Stack tecnológico
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
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.