Skip to content

Property ... is missing in type ... but required in type ... when uncertainty is introduced during assignment to variable of discriminated union typeΒ #54676

Closed
@FelixZY

Description

@FelixZY

Bug Report

πŸ”Ž Search Terms

No idea how to search for this.

πŸ•— Version & Regression Information

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

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type A =
  | {
      prop: {
        type: "number";
        num: number;
        str?: undefined;
      };
    }
  | {
      prop: {
        type: "string";
        num?: undefined;
        str: string;
      };
    };

// Expected: No error
// Actual: Property 'str' is missing in type '{ type: "number"; num: number; }' but required in type '{ type: "string"; num?: undefined; str: string; }'.
const a: A = {
  prop:
    // Introducing uncertainty in the assignment
    // appears to be key to triggering this bug
    Math.random() > 0.5
      ? {
          type: "string",
          str: "hello",
        }
      : {
          type: "number",
          num: 123,
        },
};

πŸ™ Actual behavior

Type '{ prop: { type: "string"; str: string; } | { type: "number"; num: number; }; }' is not assignable to type 'A'.
  Type '{ prop: { type: "string"; str: string; } | { type: "number"; num: number; }; }' is not assignable to type '{ prop: { type: "string"; num?: undefined; str: string; }; }'.
    Types of property 'prop' are incompatible.
      Type '{ type: "string"; str: string; } | { type: "number"; num: number; }' is not assignable to type '{ type: "string"; num?: undefined; str: string; }'.
        Property 'str' is missing in type '{ type: "number"; num: number; }' but required in type '{ type: "string"; num?: undefined; str: string; }'.

πŸ™‚ Expected behavior

No error

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions