microsoft / microsoft/TypeScript

Narrowing from `typeof x !== 'object'` incorrectly excludes functions.

Abierto
#44,855 3 comentarios 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

In Discussion Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Bug Report

🔎 Search Terms

typeof object function narrow, type narrowing

🕗 Version & Regression Information

Present in all recent versions from at least 3.3.3333 through the current nightly 4.4.0-dev.20210701

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "typeof" and "narrow"
⏯ Playground Link

Playground link

💻 Code
let x!: string|object; // |Function;
if (1 < 2) x = () => 1;

if (typeof x !== 'object') {
  useString(x); // should fail, but doesn't
}

declare function useString(s: string): void;
🙁 Actual behavior

The type narrowing for typeof x !== 'object' pruned the entire |object branch from x's type union, but typeof can return either "object" or "function" for values of type object, so this is overzealous. This causes x inside the conditional to be incorrectly narrowed to just string when we can clearly see from the earlier line that it's been assigned a function, which is incorrectly passed to useString with no complaint.

🙂 Expected behavior

Excluding "object" from typeof x should not remove |object from its type, in the same way that it doesn't narrow unknown any further. This would cause the appropriate type error from passing a function to useString.

Note that if an explicit |Function branch is added to to x's type union then the narrowing proceeds as expected.

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 el ejemplo de narrowing proporcionado; después, sigue la lógica de narrowing de tipos para typeof x !== "object". La corrección estará terminada cuando una función asignada a x no se elimine mediante narrowing y pasar x a useString produzca el error de tipo esperado; verifica el comportamiento con las versiones indicadas.

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
Bien especificado
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.