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

如何用JSDoc在mjs中实现带泛型默认值的TS重载inline函数?

用JSDoc在MJS文件中实现带泛型约束、默认值的重载函数

下面直接给出对应实现方案,结合示例代码说明:

先明确原TS函数示例(参考基准)

假设你原TS代码是类似这样的重载泛型函数:

type ValidType = string | number;

// 重载签名1:仅传入值
function processValue<T extends ValidType = string>(value: T): T;
// 重载签名2:传入值和转换函数
function processValue<T extends ValidType = string>(value: T, transform: (val: T) => T): T;

// 函数实现
function processValue<T extends ValidType = string>(value: T, transform?: (val: T) => T) {
  return transform ? transform(value) : value;
}

方案1:命名函数(MJS中用JSDoc模拟)

在.mjs文件中,通过@overload标签定义每个重载签名,配合@template声明泛型约束与默认值:

/**
 * @typedef {string | number} ValidType
 */

/**
 * @overload
 * @template {ValidType} T=string
 * @param {T} value
 * @returns {T}
 */

/**
 * @overload
 * @template {ValidType} T=string
 * @param {T} value
 * @param {(val: T) => T} transform
 * @returns {T}
 */

/**
 * @template {ValidType} T=string
 * @param {T} value
 * @param {(val: T) => T} [transform]
 * @returns {T}
 */
export function processValue(value, transform) {
  return transform ? transform(value) : value;
}

关键细节说明

  1. @typedef:先定义泛型约束的基础类型,提升复用性
  2. @overload:每个重载签名单独用这个标签开头,顺序必须在实际函数实现的JSDoc之前
  3. @template {ValidType} T=string:指定泛型T的约束(必须是ValidType的子类型)和默认值(string)
  4. 实际函数的参数:把可选的transform用[transform]标记为可选,确保类型兼容所有重载

方案2:内联函数(变量赋值的函数)

如果是内联函数(比如const fn = () => {}这种形式),用@type指定联合的重载泛型函数类型:

/**
 * @typedef {string | number} ValidType
 */

/**
 * @type {
 *   (<T extends ValidType = string>(value: T) => T) &
 *   (<T extends ValidType = string>(value: T, transform: (val: T) => T) => T)
 * }
 */
const processValue = (value, transform) => {
  return transform ? transform(value) : value;
};

关键细节说明

  • 用类型交集&将两个泛型函数类型联合,模拟重载效果
  • 每个泛型函数类型单独声明约束extends ValidType和默认值=string

TS类型检查配置

确保你的tsconfig.json中开启以下配置,让TS对.mjs文件做类型检查:

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "strict": true
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:37:42