You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript函数提前返回问题:返回指定类型时空场景处理

解决方案

要实现空列表时不返回任何内容,核心是调整函数的返回类型并修改逻辑返回undefined,具体步骤如下:

1. 修改函数返回类型

原函数返回类型为SummaryItem,强制要求返回符合接口的对象。我们需要将返回类型改为SummaryItem | undefined,允许在空列表场景下返回undefined来表示无内容:

function createChildcareItems(key: string): SummaryItem | undefined {
  // 函数逻辑
}

2. 调整空列表的返回逻辑

移除原有的默认返回条目,当childcareList为空时直接返回undefined:

3. 优化冗余循环(可选)

原函数中的for循环仅会返回第一个元素,完全可以直接取数组第一个元素简化代码,避免不必要的循环。

修改后的完整代码

export interface SummaryItem {
  label: string;
  value: string | number | undefined;
}

export enum ChildcareForDTV {
  current = 'Aktuell Betreuung Kind ',
  future = 'Zukunft Betreuung Kind ',
}

function createChildcareItems(key: string): SummaryItem | undefined {
  let childcareList = [];
  if (key.includes('current')) {
    childcareList = state['current']['childCare'];
  } else {
    childcareList = state['future']['childCare'];
  }

  // 空列表时返回undefined,不生成无效条目
  if (childcareList.length === 0) {
    return undefined;
  }

  // 直接取第一个元素生成结果(保持原逻辑仅返回第一个条目)
  const firstChildcare = childcareList[0];
  return {
    label: `${ChildcareForDTV[key as keyof typeof ChildcareForDTV]}1`,
    value: `${firstChildcare.days.toString()} Tage a CHF ${firstChildcare.rate.toString()}`
  };
}

调用时的处理(可选)

如果调用该函数的地方需要收集有效条目,可以通过过滤移除undefined:

const validItems = [
  createChildcareItems('current'),
  createChildcareItems('future')
].filter(item => item !== undefined);

内容的提问来源于stack exchange,提问作者scura s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:45:34