microsoft / microsoft/TypeScript
Narrowing discriminated union via type predicate and type assertion results in different behavior.
@gabritto ci sta già lavorando.
Dal 25/1/2024.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.4k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
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).
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Valutazione
Questa issue non è ancora stata valutata.