Skip to content

Variables type wrong unification / conditional inferenceΒ #48714

Closed
@HanabishiRecca

Description

@HanabishiRecca

Bug Report

πŸ”Ž Search Terms

unification, variable type, conditional inference

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const
    foo = { a: 1 },
    bar = { a: 1, b: 2 };

const result = Math.random() > 0.5 ?
    foo : bar;

const resolve = () => {
    if (Math.random() > 0.5)
        return foo;
    else
        return bar;
};

πŸ™ Actual behavior

result type and resolve return type inferred as foo only ({ a: number; }).

πŸ™‚ Expected behavior

result type and resolve return type obviously should be inferred as foo | bar (in some form of { a: number; } and { a: number; b: number; } union).

More info

This only happens when:

  1. foo and bar share at least 1 property.
  2. Objects used as variables. Using inline objects, types are inferred as intended.

Example with inline objects:

const result = Math.random() > 0.5 ?
    { a: 1 } : { a: 1, b: 2 };

const resolve = () => {
    if (Math.random() > 0.5)
        return { a: 1 };
    else
        return { a: 1, b: 2 };
};

Here types are inferred as expected:

{
    a: number;
    b?: undefined;
} | {
    a: number;
    b: number;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions