使用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
相关产品推荐
相关产品推荐

