microsoft / microsoft/TypeScript

Aliased Conditions with explicit type definition results in the "old" behavior

Open
#45,469 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

🔎 Search Terms

Aliased Conditions

🕗 Version & Regression Information

V4.4.0-beta / nightly

  • I was unable to test this on prior versions because it is a new feature
⏯ Playground Link

Playground link with relevant code

💻 Code
type Shape =
    | { kind: "circle", radius: number }
    | { kind: "square", sideLength: number };

function area(shape: Shape): number {
    const isCircle: boolean = shape.kind === "circle";
    if (isCircle) {
        // We know we have a circle here!
        return Math.PI * shape.radius ** 2;
    }
    else {
        // We know we're left with a square here!
        return shape.sideLength ** 2;
    }
}
🙁 Actual behavior

Adding the explicit type to "isCircle" results in that the sample breaks

Property 'radius' does not exist on type 'Shape'.
  Property 'radius' does not exist on type '{ kind: "square"; sideLength: number; }'.
Property 'sideLength' does not exist on type 'Shape'.
  Property 'sideLength' does not exist on type '{ kind: "circle"; radius: number; }'.
🙂 Expected behavior

Making the implicit type explicit, does not result in the behavior to change.

Using the sample provided by the TS 4.4 RC announcement, getting the implicit type of "isCircle" (by hovering over it) yields boolean
image
. By then explicitly defining the type (boolean), the Aliased Conditions seems to break/revert back to pre 4.4 behavior.

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.

Research direction

Start with the linked TypeScript Playground and reproduce the difference between the inferred and explicitly annotated isCircle conditions. Investigate the compiler’s control-flow narrowing for aliased conditions; done means the explicit boolean annotation preserves narrowing in both branches without the reported diagnostics.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.