Skip to content

Provide guidance for typings authors about order in union types #28044

@rkirov

Description

@rkirov

When writing a typing that has an union type, usually the authors put the least commonly used variant for last. Likely because it is the last thing they come up with, and seemingly the order in the union doesn't matter.

However, when there is a type error the error message down into the last option. This happens even with TS 3.0+ improved type errors. For example:

// typings
interface A {
  a: string;
  b: number
};

interface Other {
  o: number;
}

function f(x: A | Other): void;

// user
let x = {a: '', b: ''}; 
let y = f(x);

The error is:

  Type '{ a: string; b: string; }' is not assignable to type 'Other'.
    Property 'o' is missing in type '{ a: string; b: string; }'.

I see this issue very commonly with typings like angular.js and d3 and it is a major struggle for new-comers to TypeScript.

Usually the author of the typings has knowledge about this variant in the union is used more often, they should be guided how to write the typings to produce maximally userful errors.

That's said, as I was testing this locally, I couldn't figure out whether the declaration order matter (is interface A above interface Other) or just the union order (A | Other vs Other | A). It would be nice if TS team can say whether they would be comfortable with typings guide relying on the order here.

The same thing can be said about function overloads, but things are more complicated there because changing the order can affect not only erring code, but also code that currently typechecks.

/cc @DanielRosenwasser

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