Skip to content

Narrowing Union of objects does not return a Union of different narrowed types  #54041

Closed
@yannbriancon

Description

@yannbriancon

Bug Report

When modifying a variable with a type Union of objects, the inferred type should be the Union of the possible results.

🔎 Search Terms

  • Union
  • Narrow union

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Union and narrow

⏯ Playground Link

Playground link with relevant code

💻 Code

type Source = {
    type: 'ws'
    reader: {state: 'connecting'}
} | {
    type: 'file'
    reader: {state: number}
}

let source: Source = {type: 'file', reader:  {state: 12}}

/*
 * Error: getSourceWithState return type is 
 * {
 *   type: "ws" | "file";
 *   state: "connecting" | number;
 * } 
 * instead of
 *  {
 *   type: "file";
 *   state: number;
 * } |
 *  {
 *   type: "ws";
 *   state: "connecting";
 * } 
 */
const getSourceWithState = () => {
    return {
        type: source.type,
        state: source.reader.state
    }
}

const sourceWithState = getSourceWithState()
if (sourceWithState.type === 'file') {
    // Error
    sourceWithState.state += 1
}

🙁 Actual behavior

The return type of getSourceWithState is

{
  type: "ws" | "file";
  state: "connecting" | number;
} 

Then trying to narrow the type is impossible.

🙂 Expected behavior

The return type of getSourceWithState should be

{
  type: "file";
  state: number;
} |
{
  type: "ws";
  state: "connecting";
} 

This would make it possible to narrow the type and is also the truth.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions