gpt4 book ai didi

switch 语句中的 Typescript 类型生成问题

转载 作者:行者123 更新时间:2023-12-04 07:35:24 26 4
gpt4 key购买 nike

我有这个映射函数,它正在渲染一个对象的类型。

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 作为可选参数。这是 typescript 错误吗?我想要的是这种类型:

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

最佳答案

这不是 TypeScript 错误。这是自 TypeScript 2.7 引入以来的预期行为 improved type inference for object literals . fileNamestuffId 未包含在某些返回值中这一事实使编译器认为缺失应该反射(reflect)在返回类型中。

TypeScript 中的类型推断算法是一组启发式算法,语言设计者试图猜测在特定情况下大多数人希望看到什么样的东西。如果你不喜欢推断的类型,你可以随意 annotate the return type您的 mapStuffs() 函数与您喜欢的任何类型,编译器将对此感到满意,假设您的函数实现符合它:

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

function mapStuffs(fields: any): MappedStuff {

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
};
}
}

Playground link to code

关于switch 语句中的 Typescript 类型生成问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67775537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com