Home / Articles

Documenting custom object in JavaScript

2019-09-04T15:03:19Z.

This article describes documenting custom object in JavaScript.

Both JSDoc and TypeScript-specific syntaxes are being used.

Define type definitions

Assume we have 2 custom object types, Point2D and Point3D, we can define the types in a file:


// type-def.js

'use strict';

/**
 * @typedef {object} Point2D A point in the 2-dimensional space.
 * @property {number} x The position of the point along the x-axis.
 * @property {number} y The position of the point along the y-axis.
 */
const Point2D = {
  x: null,
  y: null
};

/**
 * @typedef {object} Point3D A point in the 3-dimensional space.
 * @property {number} x The position of the point along the x-axis.
 * @property {number} y The position of the point along the y-axis.
 * @property {number} z The position of the point along the z-axis.
 */
const Point3D = {
  x: null,
  y: null,
  z: null
};

module.exports = {
  Point2D,
  Point3D
};

Import type definitions

The type definitions can be referenced using @typedef tag and import() function. For example:


// point.js

'use strict';

/**
 * @typedef {import('./type-def').Point2D} Point2D
 * @typedef {import('./type-def').Point3D} Point3
 */

/**
 * Gets the origin in the 2-dimensional space.
 *
 * @returns {Point2D} The origin in the 2-dimensional space.
 */
const get2DOrigin = () => {
  const point = {
    x: 0,
    y: 0
  };
  return point;
};

/**
 * Gets the origin in the 3-dimensional space.
 *
 * @returns {Point3} The origin in the 3-dimensional space.
 */
const get3DOrigin = () => {
  const point = {
    x: 0,
    y: 0,
    z: 0
  };
  return point;
};

module.exports = {
  get2DOrigin,
  get3DOrigin
};

We use the @typedef tag to define the types Point2D and Point3 here, and their definitions are imported from the type definitions file.

Note that we refer to the type definition of Point3D in type-def.js with the name Point3.

IntelliSense in Visual Studio Code

With the type definitions, Visual Studio Code can give appropriate hints when we code.

IntelliSense in Visual Studio Code.

Visual Studio Code automatically suggests the 2 properties of the Point2D type.

IntelliSense in Visual Studio Code.

Property description is shown when we put the cursor over the property.

References