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

如何用JSDoc标注参数类型互相关联的函数?

JSDoc标注参数关联类型的函数方案

针对你的需求——val的类型依赖于type参数的固定取值,有两种实用的JSDoc标注方法:

方法一:使用@overload标注函数重载

这种方法适合类型组合数量不多的场景,每个重载块对应一组合法的type与val配对,编辑器会自动根据传入的type推断val的类型:

/**
 * Handles the value of "val" based on the "type" parameter.
 * @overload
 * @param {"number"} type - 指定数值类型
 * @param {number} val - 待处理的数值
 * @returns {void}
 */
/**
 * @overload
 * @param {"string"} type - 指定字符串类型
 * @param {string} val - 待处理的字符串
 * @returns {void}
 */
/**
 * @overload
 * @param {"boolean"} type - 指定布尔类型
 * @param {boolean} val - 待处理的布尔值
 * @returns {void}
 */
/**
 * @param {"number" | "string" | "boolean"} type - 参数val的类型标识
 * @param {number | string | boolean} val - 待处理的值
 * @returns {void}
 */
function example(type, val) {
  // handle "val" based on "type"
}

方法二:使用@callback定义联合函数签名

如果需要复用类型逻辑,或者类型组合较多,可以通过@callback定义多个合法的函数签名,再将函数指定为该联合类型:

/**
 * @callback ExampleHandler
 * @param {"number"} type
 * @param {number} val
 * @returns {void}
 */
/**
 * @callback ExampleHandler
 * @param {"string"} type
 * @param {string} val
 * @returns {void}
 */
/**
 * @callback ExampleHandler
 * @param {"boolean"} type
 * @param {boolean} val
 * @returns {void}
 */

/** @type {ExampleHandler} */
function example(type, val) {
  // handle "val" based on "type"
}

两种方法都能让编辑器正确识别type与val的关联关系,避免类型不匹配的错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:33:14