microsoft / microsoft/TypeScript

`in` operator narrowing (`key in obj`) doesn't work properly when key type is a string union

Abierto
#55,561 8 comentarios 3 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

in operator narrowing union

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing
⏯ Playground Link

https://www.typescriptlang.org/play?ssl=39&ssc=4&pln=20&pc=1#code/MYewdgzgLgBAYgeQQfQNIFECaBlGBeGAbQHIAzYgGhmJGIF0YBDCGUSKAbgFgAoN6eEjRZsyBADkAMpjHj0+ImXpMW-TrwCWYKAFMATqUbAd8ECBgBvXjBsxSALhjQ9WgObcetmCEfO3HgF9eXjUYXQECAAotAAcAVyhHODMYAB9LAIBKfAA+S2tbRBQMHAA6UhA9dCMAC0jIgGsdAE9svDyrTy9bDVIYRpaYLSGweKhs-hAAGx1SqZBXaNGEwibmukyPLyytwqES0QlpWXRyyurgOoHW3Pyu7qG+65GRsYnwCGnZ+cXYlbWNrsbDteAEPMEeAB6SFhPTNNxhcx6HQxPQgAAmcWMYRqJlRIAARjMALYwADuGigNScGmJMRmehgcQgJmAzB0EHsEOhrHZMAAjCEPrADvyFCRGJRqATlMxWMKPKFCQArMUECyMRzESVUAlamVg3iis5VWrPdp3Ly9fprF4q-nvSBfOYLSL21YtQGgzbcmFslkwABMQvYMAOgfF2qlxBlDDlakVwu8BOVEfVmuoksNPHDJoudVtFs6VqetuGKsDjs+MxdiwrHvWmxgPIAKrh9Gi9CwybiwENYBAaiA4lN0WBiFAqHKySZGMimRAEQADLRLmBgOdoilgVxOcxUxiwKkmGPEGD4mL6KDNJjAYwQFjokAc8ewGqMGKXsDe8FQv18gBmEMBAOADI1jFR5XYRNQxVMD0y1LMOGbGFQJgJ8OXXEBYDYKBGGGRgwBvNYWBAPo4KNEQALzM1Cw6AobGtZ5yxTACq2dH43VYhtARQx4YDbGAO0qFhhn9ExAyoY8+0pJwhxHdEYFxecoBSAkEn7dDnwgV8YAAQgMn8gA

💻 Code
// case 1
const KEYS1 = ['a', 'b'] as const;
const obj1 = {a: 'a', b: 'b'};
KEYS1.forEach(key => {
    if (key in obj1) console.log(obj1[key]);
});

// case 2
const KEYS2 = ['a', 'b'] as const;
const obj2 = {a: 'a'};
KEYS2.forEach(key => {
    if (key in obj2) console.log(obj2[key]); // TS errors when it shouldn't, as we are using `in` narrowing so that the 'b' property access doesn't happen
});

// case 3
const KEYS3 = ['b'] as const;
const obj3 = {a: 'a'}; // KEYS3 does not contain any keys of obj3
KEYS3.forEach(key => {
    if (key in obj3) console.log(obj3[key]); // if TS errors in case 2, then it should here too but it doesn't !!!
});
🙁 Actual behavior
  • in case 2 TS errors when it shouldn't, as we are using in narrowing so that there is no incorrect 'b' property access
  • in case 3 TS doesn't give any errors, when consistency disctates that it should if it did in case 2...
🙂 Expected behavior

Typescript shouldn't detect any errors in case 2. The type narrowing with the in operator ensures that we are only accessing properties that actually exist.

Additional information about the issue

No response

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 los tres casos del operador in del issue. Rastrea el estrechamiento de tipos del compilador y el comportamiento del acceso a propiedades indexadas; después, añade o actualiza una prueba de regresión para que el caso 2 sea aceptado, mientras que el caso 3 se gestione de forma coherente.

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
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.