microsoft / microsoft/TypeScript
Narrowing from `typeof x !== 'object'` incorrectly excludes functions.
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
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
💻 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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginnen Sie mit dem verlinkten TypeScript Playground und dem bereitgestellten Narrowing-Beispiel und verfolgen Sie dann die Type-Narrowing-Logik für typeof x !== "object". Die Behebung ist abgeschlossen, wenn eine x zugewiesene Funktion nicht weggenarrowt wird und die Übergabe von x an useString den erwarteten Typfehler erzeugt; überprüfen Sie das Verhalten anhand der angegebenen Versionen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Klar beschrieben
- Anfängerfreundlichkeit
- 45/100