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

如何在TypeScript中设置可选对象字段?附函数修改示例

函数修改方案:添加非必填params参数并过滤无效值

原始运行正常的函数

export const optionsFunc: Function = (token: string) => {
  const options = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    }
  };

  return options;
};

修改需求

为函数添加非必填的键值对类型params参数,同时给返回的options对象添加params字段,并且要过滤掉params中值为null、undefined或字符串'null'的无效项。

修改后的完整代码

export const optionsFunc: Function = (token: string, params?: Record<string, unknown>) => {
  const options = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  if (params) {
    const filteredParams = Object.entries(params).reduce(
      (acc, [key, value]) => {
        if (value !== null && value !== undefined && value !== 'null') {
          acc[key] = value;
        }
        return acc;
      },
      {} as Record<string, unknown>
    );
    options.params = filteredParams;
  }

  return options;
};

关键修改说明

  • 参数定义优化:把params设为可选参数(用?标记),同时用Record<string, unknown>代替any,既保证是键值对类型,又比any更符合TypeScript类型规范。
  • 可选字段添加逻辑:初始化options时不默认包含params,只有当传入有效的params时,才过滤后添加到options中。
  • 无效值过滤:通过Object.entries遍历params的键值对,用reduce筛选出值不为null、undefined和字符串'null'的项,避免无效参数被带入请求配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:50:34