Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unions within/without types should be hoisted/canonicalized to improve type compatibility #14865

Closed
weswigham opened this issue Mar 26, 2017 · 2 comments · Fixed by #30779
Closed
Labels
Declined The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript

Comments

@weswigham
Copy link
Member

TypeScript Version: 2.2.1

Code

type Style1 =
    | {
        type: "A";
        data: string;
    }
    | {
        type: "B";
        data: string;
    };

type Style2 = {
    type: "A" | "B";
    data: string;
}

const a: Style2 = { type: "A", data: "whatevs" };
let b: Style1;
a.type; // "A" | "B"
b.type; // "A" | "B"
b = a; // Unexpected compatibility error

Expected behavior:
No error on the assignment to b;

Actual behavior:

Type 'Style2' is not assignable to type 'Style1'.
  Type 'Style2' is not assignable to type '{ type: "B"; data: string; }'.
    Types of property 'type' are incompatible.
      Type '"A" | "B"' is not assignable to type '"B"'.
        Type '"A"' is not assignable to type '"B"'.

It's pretty clear that these types are equivalent to the human eye (only the discriminant differs between each member type of Style1, which makes it equivalent to Style2), however since TS compares memberwise when doing compatibility checking over the union, it never realizes that the overall type of the type field is identical.

@ahejlsberg
Copy link
Member

This sort of unification is only possible for a small subset of types. See my comment in #12052. It's not clear to me it is worth the extra work to attempt to unify the types as it would fail in almost all cases but add cost in every case.

@ahejlsberg ahejlsberg added the Suggestion An idea for TypeScript label May 17, 2017
@RyanCavanaugh RyanCavanaugh added the Declined The issue was declined as something which matches the TypeScript vision label Aug 15, 2018
@RyanCavanaugh
Copy link
Member

I think the general answer here is "Don't write types like Style1". Will revisit if something comes up where these types get manufactured from some common other process

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Declined The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants