switch 语句中的打字稿类型生成问题

时间:2021-05-31 14:22:14

标签: typescript types

我有一个渲染对象类型的映射函数。

function mapStuffs(fields: any) {
    switch (fields.type) {
        case "NewStuffs":
            return {
                type: "NewStuffs" as const,
                stuff: fields.stuff
            };
        case "StuffFile":
            const fileName = "jadflkjs";
            const stuffId = "adlkajsf";
            return {
                type: "StuffFile" as const,
                fileName,
                stuffId
            };
        default:
            return {
                type: "ExistingStuff" as const
            };
    }
}

当我构建时,生成的类型是:

mainstuff:
        | {
              stuff: string | undefined;
              type: "NewStuffs";
              fileName?: undefined;
              stuffId?: undefined;
          }
        | {
              type: "StuffFile";
              fileName: string;
              stuffId: string;
          }
        | {
              type: "ExistingStuff";
              fileName?: undefined;
              stuffId?: undefined;
          };

我不明白如何在不需要时删除 fileNamestuffId 作为可选参数。这是打字稿错误吗? 我想要的是这种类型:

mainstuff:
        | {
              stuff: string | undefined;
              type: "NewStuffs";
          }
        | {
              type: "StuffFile";
              fileName: string;
              stuffId: string;
          }
        | {
              type: "ExistingStuff";
          };

1 个答案:

答案 0 :(得分:2)

这不是 TypeScript 错误。这是自 TypeScript 2.7 引入 improved type inference for object literals 以来的预期行为。某些返回值没有包含 fileNamestuffId 的事实使编译器认为应该在返回类型中反映不存在。

TypeScript 中的类型推断算法是一组启发式算法,语言设计者在其中尝试猜测大多数人在某些情况下希望看到什么样的事物。如果您不喜欢推断的类型,您可以随意使用您喜欢的任何类型的 annotate the return type 函数,并且编译器会对此感到满意,假设您的函数实现符合它:

mapStuffs()

Playground link to code