microsoft / microsoft/TypeScript

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

Aperta
#44,855 3 commenti 3 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

In Discussion Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.4k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il TypeScript Playground collegato e con l'esempio di narrowing fornito, quindi segui la logica di narrowing dei tipi per typeof x !== "object". La correzione è completa quando una funzione assegnata a x non viene eliminata dal narrowing e il passaggio di x a useString produce l'errore di tipo previsto; verifica il comportamento rispetto alle versioni indicate.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.