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

如何在TypeScript中运行从模块导入的所有函数?

解决方案

要实现遍历导入模块中的所有函数并执行、收集返回值的需求,你可以通过遍历模块对象的属性,过滤出函数类型后执行,具体实现如下:

核心代码实现

修改get_val_list函数,利用Object.values遍历导入的模块对象,筛选出函数并执行:

import * as val_funcs from "path/to/val_func/file";

function get_val_list() {
  // 遍历模块所有值,过滤出函数并执行,收集返回结果
  return Object.values(val_funcs)
    .filter((item): item is Function => typeof item === "function")
    .map(func => func());
}

关键细节说明

  • 过滤函数:使用typeof item === "function"确保只处理函数类型的导出项,避免误执行非函数导出(比如类型常量等)。
  • 类型安全:添加item is Function类型守卫,让TypeScript明确知道过滤后的项是函数,避免类型报错。
  • 灵活扩展:后续只需在文件1中新增导出函数,无需修改get_val_list的代码,新增函数会自动被遍历执行,完全符合你“灵活接入”的需求。

有效搜索术语

如果后续需要拓展相关功能,可以用这些关键词搜索:

  • TypeScript iterate over imported module functions
  • Dynamic function execution from ES module
  • Filter functions from imported object in TypeScript

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:05:19