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

使用JSDoc的@typedef结合泛型@callback时类型推断异常问题

解决JSDoc泛型回调typedef的类型推断问题

你的代码中,MyType里的myFunction仅引用了泛型回调MyFunction,但没有保留泛型参数的传递能力,导致调用时JSDoc无法推断T的具体类型,最终返回any。以下是两种可行的修复方案:

方案一:给MyType添加泛型参数

将泛型参数从MyFunction传递到MyType,让类型系统能明确回调的参数和返回类型:

/**
 * @template T
 * @callback MyFunction
 * @param {T} val
 * @return {T}
 */

/**
 * @template T
 * @typedef MyType
 * @property {MyFunction<T>} myFunction
 */

// 使用时指定泛型类型
/** @type {MyType<string>} */
const foo = {
  myFunction: (val) => val
};
const bar = foo.myFunction('a string'); // bar的类型为string

方案二:直接在属性中定义泛型回调

如果不需要单独复用MyFunction类型,可以直接在MyType的属性上定义泛型箭头函数,让JSDoc自动推断类型:

/**
 * @typedef MyType
 * @property {<T>(val: T) => T} myFunction
 */

/** @type {MyType} */
const foo = {
  myFunction: (val) => val
};
const bar = foo.myFunction('a string'); // bar的类型为string

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:30:59