【发布时间】:2022-10-07 20:22:31
【问题描述】:
我正在从函数返回 SummaryItem 类型的项目
export interface SummaryItem {
label: string;
value: string | number | undefined;
}
我的目标是在 childcareList 为空时不返回条目。目前我正在返回一个条目“Aktuell Betreuung Kind”:“[]”这不是必需的。
function createChildcareItems(key: string): SummaryItem {
let childcareList = [];
if (key.includes('current')) {
childcareList = state['current']['childCare'];
} else {
childcareList = state['future']['childCare'];
}
if (childcareList.length > 0) {
for (let i = 0; i < childcareList.length; i++) {
return {
label: ChildcareForDTV[key as keyof typeof ChildcareForDTV].concat((i + 1).toString()),
value: childcareList[i]['days'].toString().concat(' Tage a CHF ').concat((childcareList[i]['rate']).toString()),
}
}
}
return {
label: ChildcareForDTV[key as keyof typeof ChildcareForDTV],
value: '[]',
}
}
ChildcareForDTV 的定义如下:
export enum ChildcareForDTV {
current = 'Aktuell Betreuung Kind ',
future = 'Zukunft Betreuung Kind ',
}
有没有办法以某种方式提前从函数返回?
我试过没有最终回报,但这是不可能的。我也试过
if (childcareList.length == 0) {
return
}
但这会产生一个错误,我猜是因为接口需要一个标签和一个值。
【问题讨论】:
-
key as keyof typeof ChildcareForDTV<-- 这有点骇人听闻。相反,您应该限制function createChildcareItems的key参数,这样如果key: string不是有效的keyof值,您将收到编译时错误。 -
为什么你不能简单地从
createChildcareItems做return null? -
@Dai 如果我返回 null 我会得到 Type '{ null: any; }' 不可分配给类型“SummaryItem”。
-
将返回类型更改为
SummaryItem | null,并更新createChildcareItems的所有调用站点以检查它是否返回null并采取相应措施。 -
“我的目标是在 childcareList 为空时不返回条目。”然后你必须在你的返回类型中指定它;按照您声明它的方式,您说过它返回一个 SummaryItem,但显然您不希望它总是返回一个。
标签: typescript