镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Variable loses type narrowing when passed as object literal #57013

Description

@jasonaden

🔎 Search Terms

object literal type inference
enum type narrowing

🕗 Version & Regression Information

  • This changed between versions 5.0.4 and 5.1.6

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.3#code/FAUwdgrgtgBAogN3AFwM4wN7BvAanAOQBUBGGAXhgHJEUYSqAabPQogJgutrGRnabAAvsGABLXiABOAMwCGAYxAwA4uGliFPPlhwgkvAnKggAXPANoA3CwAOUgPa3pyMSFQB+c2H3SbI8UlZRWVtEm1MFl9DYzMLFFQAOjh8YhIbHHsnFzdUc10cGAATOWQ5c1RkKQkAcxYhf1EJZGl5JXjedgiC6OQjE3NtJJS2dgyYLOcpV3d8lhwSsoqq2vrG4GQAT2cO5CJt9y5gAB9VdWqtSxPd8KvT7S6r4AUHMEqYSFhKAFlSgAtEjIADYOBxSAAUv2QAKkcjARQcUHBAEoYAAqegABlRAGp6DZnq93r1+spKJ8YAA+GAAVhgHl2w1SpBgg0sTNGBIA9FyYEQ-mJ0EgpKgxK8YPIxEDUMAskpUKhtOCepZScxMo4pjM8pFCsVSuUYAAib6bXYwAAiBqN9WEyO5vP5gpgwtF4oA7mCANYyl5vPiLORcFUoNV2TU5Wa6wqB8wms0RK1lG04EQNWWOeWKyzgwP20QyCBgBSucVy9zZlDg3pslD7ZyoVEFP2oBxAkCJEE1auWfMiIA

💻 Code

enum Events {
  EVENT1 = 'Event 1',
  EVENT2 = 'Event 2',
}

interface GenericEvent {
  eventName: Events;
  properties?: never;
}

interface Event1Event {
  eventName: Events.EVENT1;
  properties: {
    data: string
  };
}

interface Event2Event {
  eventName: Events.EVENT2;
  properties: {
    data: string
  };
}

type EventTypes = 
| GenericEvent
| Event1Event
| Event2Event

const num = Math.floor(Math.random() * 10) + 1;

const eventName = num > 5 ? Events.EVENT1 : Events.EVENT2;

// This version fails on properties: Type '{ data: string; }' is not assignable to type 'undefined'
processEvent({
  eventName,
  properties: {
    data: "My Event Data"
  }
});

// This version works
const data = {
  eventName,
  properties: {
    data: "My Event Data"
  }
};
processEvent(data);

function processEvent(event: EventTypes) {
  console.log(event);
}

🙁 Actual behavior

The event passed to processEvent behaves differently if assigned to a const prior to being passed in.

🙂 Expected behavior

Both should be the same result. It's also worth noting that in the repro provided assignment to a const data = ... works to resolve the problem. But in my code this doesn't end up working and instead I need to explicitly state that eventName can only be one of the two Events values in the ternary.

Additional information about the issue

No response

Activity

  1. RyanCavanaugh commented on Jan 11, 2024

    @RyanCavanaugh
    Member

    Both should be the same result.

    Which result is correct?

  2. jasonaden commented on Jan 11, 2024

    @jasonaden
    Author

    Both the working version and the currently failing version above should work. They both worked prior to 5.1.6 (didn't get into patches leading up to 5.1.6 so may have been introduced at first release of 5.1).

  3. RyanCavanaugh commented on Jan 23, 2024

    @RyanCavanaugh
    Member

    Bisects to #53709

  4. ahejlsberg commented on Mar 6, 2024

    @ahejlsberg
    Member

    The repro here is an example of the pattern covered by #30779, i.e. relating a source object type to a discriminated union of target object types where no single target type covers the possible set of source values, but the full union of target types do. We have limited support for this pattern, and we handle it by decomposing the source type into a union as long as that union doesn't have more than 25 constituents. For example, in

    type A = { kind: "a", data: string };
    type B = { kind: "b", data: string };
    
    declare const ab: "a" | "b";
    
    let x: A | B = { kind: ab, data: "hello" };

    we decompose the object literal into a union of the two possible values { kind: "a", data: "hello" } | { kind: "b", data: "hello" } in order to successfully relate it to A | B.

    However, we attempt no such decomposition when checking excess properties in object literals. Consider

    type X = { kind: "a" | "b", data: undefined };
    type A = { kind: "a", data: string };
    type B = { kind: "b", data: string };
    
    declare const ab: "a" | "b";
    
    let x: X | A | B = { kind: ab, data: "hello" };  // Error
    
    const obj = { kind: ab, data: "hello" };
    
    let y: X | A | B = obj;  // Ok

    Above, when checking the object literal for excess properties, we first discriminate the target type X | A | B by the kind property specified in the object literal. It has type "a" | "b", for which we find that only X matches. We then error because the data property is a string that isn't assignable to undefined. Since we only do excess property checking for object literals, there's no error when we first assign the object literal to a variable (but the assignment only succeeds because of #30779).

    Considering the rarity of this problem and the complexity of incorporating the decomposition pattern into excess property checking, I'm going to call this a design limitation.

  5. added
    Design LimitationConstraints of the existing architecture prevent this from being fixed
    and removed
    Needs InvestigationThis issue needs a team member to investigate its status.
    on Mar 6, 2024
  6. typescript-bot commented on Mar 9, 2024

    @typescript-bot
    Contributor

    This issue has been marked as "Design Limitation" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

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