microsoft / microsoft/TypeScript

Incorporating exhaustiveness analysis into the control flow of if statements.

Abierto
#56,527 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Domain: check: Control Flow Possible Improvement
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

🔍 Search Terms

"initialization", "variable", "inference", "assignment", "assigned", "automatic detection"

✅ Viability Checklist
⭐ Suggestion

One's code may implicitely involve that all cases have been processed in an if-else structure. TS does detect it with switch statements, however it does not detect it with if-else clauses.

Consider the following example:

type Dinosaur = "triceratops" | "brachiosaurus"

const myCollectionOfDinosaurs: Dinosaur[] = ["triceratops", "brachiosaurus"]

const randomKey = Math.floor(Math.random() * myCollectionOfDinosaurs.length)
const randomlyChosenDinosaur: Dinosaur = myCollectionOfDinosaurs[randomKey]

let dinosaurGreeting: string

if (randomlyChosenDinosaur === "triceratops") dinosaurGreeting = "Hello triceratops!"
else if (randomlyChosenDinosaur === "brachiosaurus") dinosaurGreeting = "Hello brachiosaurus!"

console.log(dinosaurGreeting)

TS complains on the last line because it says dinosaurGreeting is used before being assigned.

Replacing the if-else clause with a switch statement fixes the problem. However it would be great if TS did support this feature for if-else clauses too.

📃 Motivating Example

I'd use the dinosaurs example above, and assert that this feature would remove unnecessary constraints in the language.

💻 Use Cases
  1. What do you want to use this for?
    Writing some meaningful code with less constraints, shaping it more precisely and remaining safe from type-related problems.
  2. What shortcomings exist with current approaches?
    Most current approaches involve working around the way you intend your code to work. For example I can use !: when typing the variable, or initialize the variable with a default variable, or define it anywhere it is initialized, but all these solutions would imply thinking the code differently, in a way that is less compatible with my need.
    The best approach is using a switch statement instead of an if-else clause, which doesn't impact the logic of the code.
  3. What workarounds are you using in the meantime?
    Replacing the if-else clause with a switch statement.

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

Empieza reproduciendo el ejemplo del dinosaurio del issue y compara su comportamiento de asignación definitiva con el de la sentencia switch equivalente. Rastrea el análisis de flujo de control y de exhaustividad del compilador para determinar dónde se manejan las ramas if-else; se considera terminado cuando las ramas exhaustivas ya no producen el error de variable usada antes de ser asignada sin cambiar el JavaScript emitido.

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
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.