microsoft / microsoft/TypeScript

Narrow object property indexed by another object's property of unique symbol type (like `Symbol.iterator`)

Abierto
#63,059 0 comentarios 0 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

type guard, narrowing, control flow analysis, property, index, known type, symbol type, bracket notation, unique symbol, known symbol, Symbol.iterator, #10530

✅ Viability Checklist
⭐ Suggestion

This is yet another version of #10530 that doesn't seem to be covered by cases in #56389 or #61176. It might even be covered by #62247 and/or #62314 but I'm not sure. TypeScript already narrows by bracket notation when the key is a unique symbol variable:

declare const s: unique symbol;
declare const x: {}
if ((s in x) && (typeof x[s] === "string")) { x[s].toUpperCase(); }; // okay

but this no longer works if the key is a unique symbol property of another object:

declare const obj: { readonly s: unique symbol }
declare const x: {}
if ((obj.s in x) && (typeof x[obj.s] === "string")) { x[obj.s].toUpperCase(); } // error

The suggestion here is to make the latter work like the former.

📃 Motivating Example

See https://stackoverflow.com/questions/79877994/why-does-my-test-for-an-iterableiterator-fail

Consider

function f(x: object) {
    if ((Symbol.iterator in x) && (typeof x[Symbol.iterator] === "function")) {
        x[Symbol.iterator].length; // error
        //~~~~~~~~~~~~~~~~ <-- Object is of type 'unknown'.(2571)
    }
}

This just looks like a somewhat unfortunate gap in type guarding, where TS knows Symbol.iterator is a unique symbol but won't actually do the narrowing unless you put that unique symbol in its own variable directly:

function f(x: object) {
    const symbolIterator: typeof Symbol.iterator = Symbol.iterator;
    if ((symbolIterator in x) && (typeof x[symbolIterator] === "function")) {
        x[symbolIterator].length; // okay
    }
}

Playground link

💻 Use Cases
  1. What do you want to use this for? To allow people to type guard on Symbol.XXX properties
  2. What shortcomings exist with current approaches? People apparently don't like to copy things to new variables just for narrowing.
  3. What workarounds are you using in the meantime? Copy things to new variables. The obvious approach is the old standby, where we replace if (f(obj[k])) g(obj[k]) with const objK = obj[k]; if (f(objK)) g(objK)

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 leyendo el análisis del flujo de control y el manejo de los guardas de tipo de TypeScript para la notación con corchetes, comparando el ejemplo funcional de una variable unique-symbol con los casos fallidos obj.s y Symbol.iterator. Revisa los issues relacionados #10530, #56389, #61176, #62247 y #62314, y después usa el ejemplo proporcionado de Playground para verificar que el acceso a propiedades realiza el narrowing de forma coherente cuando el cambio esté completo.

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.