microsoft / microsoft/TypeScript

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

Open
#45,770 0 comments 3 reactions 1 assignee View on GitHub

@gabritto is already working on this.

Since Jan 25, 2024.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

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).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.