Typescript: Discriminated union types better error reporting

Created on 12 Sep 2016  路  4Comments  路  Source: microsoft/TypeScript

This the example from docs:
image

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

interface Circle {
    kind: "circle";
    radius: number;
}

type Shape = Square | Rectangle | Circle;

let shape: Shape = {
  kind: "square",
  width: 10,
  height: 10
}

So we create object with type Shape of kind square and try to pass incorrect other props (for this kind), and TS emits the error that object is no assignable to last type that is in union (Circle in this case). I believe it would be better if TS would recoginze that we are trying to make Square type in this case and emitted corresponding error message.

Committed Fixed Suggestion

Most helpful comment

Work item for 2.2: Figure out how to detect discriminated unions and report errors based on a matched discriminant field

All 4 comments

There's another recent issue #10849 that talks about this and other discriminated unions issues. Perhaps one could be merged into the other?

Yes, this is a subset of the issue #10849 that reported a few days back.

Work item for 2.2: Figure out how to detect discriminated unions and report errors based on a matched discriminant field

Fix is up at #14006

Was this page helpful?
0 / 5 - 0 ratings

Related issues

manekinekko picture manekinekko  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

dlaberge picture dlaberge  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments