microsoft / microsoft/TypeScript

Union type resolving to one side of the union when spread operator is used

Open
#42,771 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Bug Report

This issue may be related but they were different enough to warrant a write up here: https://github.com/microsoft/TypeScript/issues/42665

When assigning a union type to a variable, which is immediately instantiated as an object that could possibly be either type at run time, and the spread operator is used to "optionally" apply a property, the type of the variable falls to the type without the extra properties automatically.

🔎 Search Terms

Spread operator, object, union type

🕗 Version & Regression Information

This changed between versions 3.7.5 and 3.8.3.

⏯ Playground Link

Playground link with relevant code

💻 Code
interface Foo {
    bar: string;
}

type Bar = Foo & {
    baz: string;
}

const produceBoolean = () => Math.random() > 0.5;

const obj: Foo | Bar = {
    bar: 'baz',
    ...(produceBoolean() && {
        baz: 'bar'
    })
}

if ('baz' in obj) { // obj is "Foo" here
    console.log(obj); // obj is "never" here
}
🙁 Actual behavior

Instead of remaining a union type until some discrimination was made, it assumed the object was the side of the union without extra properties.

🙂 Expected behavior

It would remain possibly either or any type in the union until discriminated in the code.

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 reproduction and compare its behavior across the reported 3.7.5 and 3.8.3 versions. Trace the type-checking path for object spread into a union, then verify that the resulting value remains a union and that the 'baz' in obj check narrows it correctly.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.