microsoft / microsoft/TypeScript

Compiler warning for always true/false strict inequality expression

Abierto
#28,569 0 comentarios 6 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

In Discussion Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

Search Terms

type guard warning if always true false non-identity inequality

Suggestion

The compiler should emit a warning if it can determine that an expression using a strict inequality check (!==) always returns true or false. It already does this for strict equality checks (===).

Use Cases

Like the warnings for the strict equality check, it helps identifying unreachable code blocks or unnecessary if blocks which can get introduced during refactoring of existing code or during carefree creation of new code.

Examples

The following function definition emits an error ("This condition will always return 'false' since the types '"abc"' and '"xyz"' have no overlap."):

function fn(p: "abc") {
  if (p === "xyz") {
    
  }
}

But this function definition compiles just fine (a possible error message could be "This condition will always return 'true' since the types '"abc"' and '"abc"' overlap completely":

function fn2(p: "abc") {
  if (p !== "abc") {
    
  }
}

It even correctly type-guards the type of p inside the if block (it becomes never).

Two other scenarios which trigger this non-warning, but could be harder to detect:

// typeof checks
function fn3(p: string) {
  if (typeof p !== "string") {

  }
}

// the length of a tuple
function fn4(p: []) {
  if (p.length !== 0) {

  }
}

The last example doesn't type-guard the value of p correctly to never even though p.length is correctly of type 0, maybe this is a separate feature request.

Problems / Discussion Points

  • I'm not sure whether this qualifies as a breaking change, since it introduces a warning for code constructs which compile totally fine at the moment.
  • This could be extended for other checks as well (e.g. for the </<= and >/>= operators) even though this would be pretty edge-casey.

Checklist

My suggestion meets these guidelines:

  • (Unsure) 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

No se indica ningún archivo, prueba ni punto de entrada del compilador. Empieza por localizar los diagnósticos existentes para las comprobaciones de igualdad estricta y compara cómo se analizan la desigualdad estricta, typeof y las expresiones de longitud de tuplas. La tarea estará terminada cuando se añadan diagnósticos para las condiciones !== que sean demostrablemente siempre verdaderas o siempre falsas, sin cambiar el JavaScript generado.

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.