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

如何在JSDoc(或TypeScript)中记录对象的自定义函数类型并让VSCode IntelliSense生效

没问题,我来帮你搞定这个函数类型复用的问题!

可行解决方案:两种正确的可复用函数类型定义方式

要实现和 Exhibit A 完全一致的效果,同时支持类型复用,你可以用以下两种标准的 JSDoc 写法:

方案1:使用@callback标签(推荐)

@callback是 JSDoc 专门为定义可复用函数类型设计的标签,能完美解析参数,且支持跨多处引用。

/**
 * @typedef {Object} Point
 * @property {number} x - The X Coordinate
 * @property {number} y - The Y Coordinate
 */

/**
 * @callback AddCoordinateHandler
 * @param {string} x - The X coordinate string to update
 * @param {string} y - The Y coordinate string to update
 * @returns {void}
 */

/**
 * @typedef {Object} Shape
 * @property {Point} startCoordinate - the starting coordinate
 * @property {Point[]} coordinates - An array of point coordinates
 * @property {(x:string, y:string) => void} addCoordinate - Updates the point (inline version)
 * @property {AddCoordinateHandler} addCoordinateOne - Updates the point (reusable callback type)
 */

/** @type {Shape} */
const square = {
  addCoordinateOne: (x, y) => {
    // 编辑器会正确提示x/y的类型为string
  }
};

方案2:使用@typedef直接定义函数签名

如果你更习惯用@typedef,可以直接用箭头函数语法声明函数类型,同样能实现复用和参数解析:

/**
 * @typedef {Object} Point
 * @property {number} x - The X Coordinate
 * @property {number} y - The Y Coordinate
 */

/**
 * @typedef {(x: string, y: string) => void} AddCoordinateFn
 */

/**
 * @typedef {Object} Shape
 * @property {Point} startCoordinate - the starting coordinate
 * @property {Point[]} coordinates - An array of point coordinates
 * @property {(x:string, y:string) => void} addCoordinate - Updates the point (inline version)
 * @property {AddCoordinateFn} addCoordinateTwo - Updates the point (reusable typedef function type)
 */

/** @type {Shape} */
const square = {
  addCoordinateTwo: (x, y) => {
    // 同样能正确识别参数类型
  }
};

为什么你的原有写法失效?

  • Exhibit B:用@typedef {Function} addCoordinateOne的方式,只是笼统声明了这是一个函数类型,但JSDoc(以及VS Code等编辑器的类型服务)无法将后续的@param标签和这个函数类型正确绑定,导致参数解析失败。
  • Exhibit C:@function标签是用来标记实际存在的函数实体,而不是定义可复用的类型模板。所以当你在Shape的属性里引用addCoordinateTwo时,JSDoc找不到对应的类型定义,自然完全失效。

内容的提问来源于stack exchange,提问作者sgarcia.dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 18:54:06