microsoft / microsoft/TypeScript

Type narrowing down on a union type with null results in incorrect type when applying `typeof`

Offen
#44,914 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bug Domain: check: Control Flow
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

Bug Report

🔎 Search Terms

type narrowing down, typeof

🕗 Version & Regression Information

I've tested all versions until 4.4.0 (Nightly)

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.4.0-dev.20210706#code/C4TwDgpgBAwg9gO2AQwJYIgJygXigbygGNEV0sAuA0SKgIgDM446BfKAH2vAnoCNkmNpygIArgBsJUVgFgAUAoZiERYKkRRgEAM7AAFOjBjgVeEjQZMASgIKoDqKgZRDCY8AB0JC+UwB+TxpoHFCoAHImOHDbfHtHBIB6RKgAdzhMAGsdeISHZCIiCDBgHQAxZjcPb1JLLGsAbly8gqKS8sr8YPootmtmpJSAEThdUThgNIzsgcdW4tKKuCqTGt8rKGQdLR44FyNVnzIrfvk8ucKFjuWunh7mYS2dyD2nd0Pav1OEuXlfpRUag0CE2l3aSxWpm4tCgjAerFirCAA

💻 Code
type Container = { container: {type: "foo"} | {type: "bar"} | null }

function test(input: Container) {
    if (input.container?.type === 'foo') {
        // works
        acceptsFoo(input.container);
        acceptsFoo({type: "foo"})
        // Does not works
        acceptsFoo(input.container as typeof input.container)
        acceptsFoo({type: "foo"} as typeof input.container)
		/**
Error:
 Argument of type '{ type: "foo"; } | null' is not assignable to parameter of type '{ type: "foo"; }'.
  Type 'null' is not assignable to type '{ type: "foo"; }'.(2345) \
**/
    }
}

function acceptsFoo(input: {type: "foo"}) {}
🙁 Actual behavior

input.container and input.container as typeof input.container are not equivalent.

🙂 Expected behavior

input.container and input.container as typeof input.container should be equivalent.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduzieren Sie das gemeldete Narrowing-Verhalten im verknüpften TypeScript Playground mithilfe des bereitgestellten Container und der Testfunktion. Beginnen Sie damit, die Verarbeitung des Type-Checkers für das Narrowing optionaler Eigenschaften und typeof-Assertions nachzuverfolgen; abgeschlossen ist die Aufgabe, wenn input.container und input.container as typeof input.container ohne den Nullability-Fehler gleichwertig behandelt werden.

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
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.