microsoft / microsoft/TypeScript

Narrowing discriminated union via type predicate and type assertion results in different behavior.

Offen
#45,770 0 Kommentare 3 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@gabritto arbeitet bereits daran.

Seit 25.1.2024.

Needs Investigation
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

Bug Report

🔎 Search Terms

type predicate discriminated union

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about v4.5.0-dev.20210907
⏯ Playground Link

Playground link with relevant code

💻 Code
declare const fruit: { kind: 'apple'} | { kind: 'banana' } | { kind: 'cherry' }

declare function isOneOf<T, U extends T>(item: T, array: readonly U[]): item is U
if (isOneOf(fruit.kind, ['apple', 'banana'] as const)) {
    fruit.kind // 'apple' | 'banana'
    fruit // { kind: 'apple'} | { kind: 'banana' } | { kind: 'cherry' }
} else {
    fruit.kind // 'cherry'
    fruit // { kind: 'apple'} | { kind: 'banana' } | { kind: 'cherry' }
}

declare function isDefinitelyOneOf<T, U extends T>(item: T, array: readonly U[]): asserts item is U
isDefinitelyOneOf(fruit.kind, ['apple', 'banana'] as const)
fruit.kind // 'apple' | 'banana'
fruit // { kind: 'apple'} | { kind: 'banana' }
🙁 Actual behavior

Type assertion does the correct thing, but the equivalent type predicate results in an odd scenario where the property is correctly narrowed, but the union object is not narrowed.

🙂 Expected behavior

Type assertion and type predicate have the same narrowing behavior, and only differ on whether the code branches or throws.

I would also expect the type predicate to either narrow neither the property nor the object or both the property and the object (like the type assertion does).

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.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

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