sgarcia.dev
sgarcia.dev

Reputation: 6190

How to document function custom types in JSDoc (or TypeScript?) and reference them so VSCode IntelliSense works

I am trying to document custom function types as part of an object, any help would be greatly appreciated:

Context of the problem

Here is a simple object declaration with some function properties (addCoordinate, addCoordinateOne, addCoordinateTwo) which we will go over as 3 exhibits, and why none of these work.

/**
 * @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 = {}

Exhibit A

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

This works fully, but isn't reusable like I need.

Exhibit A

Exhibit B

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

This sort of works, as it detects the custom function type. But it doesn't parse parameters properly. I made sure to follow the documentation for the @typedef tag: https://jsdoc.app/tags-typedef.html

Exhibit B

Exhibit C

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

This fails completely. Despite being the recommended approach by JSDoc's @function documentation. https://jsdoc.app/tags-function.html

The Question

Is there any way I could get Exhibit B or C working like Exhibit A?

Upvotes: 5

Views: 3536

Answers (1)

Matt Schlosser
Matt Schlosser

Reputation: 1044

You can change Exhibit A to a typedef:

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

Edit: Or more verbosely, you can use the @callback tag:

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

Then reuse as needed:


/**
 * @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
 */

Result:

If using the shorthand syntax, no paramater descriptions are available. vs code hover showing expected Intellisense hint

If using the @callback syntax, descriptions are provided for each paramater: vs code hover showing Intellisense hint with param description

Upvotes: 6

Related Questions