【问题标题】:How to document function custom types in JSDoc (or TypeScript?) and reference them so VSCode IntelliSense works如何在 JSDoc(或 TypeScript?)中记录函数自定义类型并引用它们以便 VSCode IntelliSense 工作
【发布时间】:2022-09-30 00:46:36
【问题描述】:

我正在尝试将自定义函数类型记录为对象的一部分,我们将不胜感激任何帮助:

问题的背景

这是一个简单的对象声明,其中包含一些函数属性(addCoordinate、addCoordinateOne、addCoordinateTwo),我们将通过 3 个展示来讨论它们,以及为什么这些都不起作用。

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

/**
 * @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
 * @property {addCoordinateOne} addCoordinateOne - Updates the point
 * @property {addCoordinateTwo} addCoordinateTwo - Updates the point
 */

/** @type {Shape} */
const square = {}

展品 A

@property {(x:string, y:string) => void} addCoordinate - Updates the point

这完全有效,但不能像我需要的那样可重复使用。

展品 B

/**
 * @typedef {Function} addCoordinateOne
 * @param {string} X
 * @param {string} Y
 */

这个有点有效,因为它检测到自定义函数类型。但它不能正确解析参数。我确保遵循@typedef 标签的文档: https://jsdoc.app/tags-typedef.html

展品 C

/**
 * @function addCoordinateTwo
 * @param {string} X
 * @param {string} Y
 */

这完全失败了。尽管是 JSDoc 的 @function 文档推荐的方法。 https://jsdoc.app/tags-function.html

问题

有什么办法可以让 Exhibit B 或 C 像 Exhibit A 一样工作?

    标签: javascript typescript visual-studio-code jsdoc


    【解决方案1】:

    您可以将 Exhibit A 更改为 typedef:

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

    编辑:或者更详细地说,您可以使用@callback 标签:

    /** 
     * @callback addCoordinate
     * @param {number} x - The x coordinate
     * @param {number} y - The y coordinate 
     * @returns {void}
     */
    

    然后根据需要重用:

    
    /**
     * @typedef {Object} Point
     * @property {number} x - The X Coordinate
     * @property {number} y - The Y Coordinate
     */
    
    /**
     * @typedef {Object} Shape
     * @property {Point} startCoordinate - the starting coordinate
     * @property {Point[]} coordinates - An array of point coordinates
     * @property {addCoordinate} addCoordinate - Updates the point
     * @property {addCoordinate} addCoordinateOne - Updates the point
     * @property {addCoordinate} addCoordinateTwo - Updates the point
     */
    

    结果:

    如果使用简写语法,则没有可用的参数描述。

    如果使用 @callback 语法,则为每个参数提供描述:

    【讨论】:

    • 为什么你没有收到错误Expected 2 arguments, got 0
    • 那是...不是我所期望的,但我很惊讶它的工作原理哈哈。这太妙了。如果几天后没有其他问题,将奖励接受的答案。正在寻找使用扩展 @param 语法的东西,以便能够记录每个参数的解释。谢谢马特。
    • 编辑了答案,因为我还发现有一个类似于 typedef 的 @callback 语法。
    • 这解决了我的问题,谢谢@MattSchlosser!
    猜你喜欢
    • 2016-04-24
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2022-01-05
    • 2022-01-22
    相关资源
    最近更新 更多