microsoft / microsoft/TypeScript

Union with non-distinct discriminating property breaks inference somewhat (confusing error messages, invalid intellisense)

未关闭
#40,934 8 条评论 1 个 reaction 已指派 1 人 在 GitHub 查看

还没有人认领这个 Issue。

Domain: Error Messages Experience Enhancement
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

TypeScript Version: 4.0.2

Search Terms: discriminated union, error messages

Code

type Action = {
    type: 'action1';
    payload: {
        property1: string;
    };
} | {
    type: 'action1';
    payload: {
        property2: number;
    };
} | {
    type: 'action2';
    payload: {
        property3: boolean;
    };
}

const action: Action = { // Actual error is here
    type: 'action1',
    payload: {
        property3: true // Expected error here
    }
}

Expected behavior:

Expected error at action.payload.property3 declaration, perhaps something like:

Object literal may only specify known properties, and 'property3' does not exist in type '{ property1: string; } | { property2: number; }'.

Also, once the object has been refined by the type action1, intellisense should only provide property1 and property2 as a suggestion when declaring the payload.

Actual behavior:

An error message at the first line of the declaration:

Type '{ type: "action1"; payload: { property3: true; }; }' is not assignable to type 'Action'.
  Type '{ type: "action1"; payload: { property3: true; }; }' is not assignable to type '{ type: "action2"; payload: { property3: boolean; }; }'.o
      Type '"action1"' is not assignable to type '"action2"'.(2322)

Also, once the object has been refined by the type action1, intellisense still provides property3 as a suggestion when declaring the payload.

Playground Link: https://www.typescriptlang.org/play?#code/C4TwDgpgBAggxsAlgewHZQLxQN4CgoFSiQBcUA5AIYIqoCM5A3PoWJSADbKUAmZehQVDAAnZJBGg6ZAM7ARiVAHNmggL7M1UAD44WBYhDJUaaBqtbsuvfvqGjxESSABMZVAFcAtgCMnFgg1cLV0BQkNjaiQ0FyY7Nk5uPj0hVjEJUABmMh9kZA4ISlQAqCC1XFw4NDkoKNoyeGj0LDCDcCMKOrNyABp4qyTbVIIHDJBsohEPCDtytSA

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。