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

如何为嵌套函数正确类型标注以避免使用any?

为嵌套路径图标生成函数添加TypeScript类型标注

通过定义统一的返回值类型、明确递归函数的类型约束,可完全移除代码中的any类型,以下是修改后的完整实现:

修改后的代码

const testIcons = {
  large: {
    image_title1: 'some image 1',
    action: {
      image_title2: 'some image 2',
      light: {
        image_title3: 'some image 3',
      },
    },
  },
};

// 定义每个图标项的结构类型
type IconItem = {
  title: string;
  value: string;
};

// 定义嵌套图标对象的类型
type BaseIconPath = {
  [key: string]: BaseIconPath | string;
};

// 递归遍历嵌套路径的函数,明确输入输出类型
const getNestedIcons = (basePath: BaseIconPath, parentPath: string): IconItem[] => {
  return Object.keys(basePath).flatMap((key) => {
    const currentPath = `${parentPath}.${key}`;
    const value = basePath[key];
    
    // 排除null的误判(typeof null === 'object')
    if (typeof value === 'object' && value !== null) {
      return getNestedIcons(value, currentPath);
    }
    
    return [{ title: currentPath, value: currentPath }];
  });
};

// 主函数,明确输入输出类型
const getIconsListFromUiKit = (iconSize: keyof typeof testIcons): IconItem[] => {
  const basePath = testIcons[iconSize] as BaseIconPath;

  return Object.keys(basePath).flatMap((key) => {
    const value = basePath[key];
    
    if (typeof value === 'object' && value !== null) {
      return getNestedIcons(value, key);
    }
    
    return [{ title: key, value: key }];
  });
};

// 调用示例,返回类型为IconItem[]
const icons = getIconsListFromUiKit('large');

核心修改说明

  • 统一返回类型:新增IconItem类型,明确每个图标项的结构,替代模糊的any
  • 递归函数类型约束:为getNestedIcons指定参数类型(嵌套对象BaseIconPath和父路径字符串),返回类型为IconItem[],让TypeScript能正确推导递归过程中的类型
  • 优化数组处理:用flatMap替代map+flat(Infinity),简化代码的同时让数组类型推导更直接
  • 空值防护:增加value !== null判断,避免将null误判为对象导致递归错误
  • 移除所有any:所有变量和函数的类型都明确标注,完全消除类型模糊性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:50:26