How to generate documentation for enum members when generating TypeScript definitions from JavaScript?

Viewed 98

Following the official instructions in Creating .d.ts Files from .js files, I am trying to generate definitions for a JSDoc @enum.

/**
 * The direction enum.
 * 
 * @enum {number}
 */
const Direction = {
  /**
   * Up direction.
   * 
   * @type {number}
   * @constant
   */
  Up: 1,
  /**
   * Down direction.
   * 
   * @type {number}
   * @constant
   */
  Down: 2,
  /**
   * Left direction.
   * 
   * @type {number}
   * @constant
   */
  Left: 3,
  /**
   * Right direction.
   * 
   * @type {number}
   * @constant
   */
  Right: 4,
};
export default Direction;

For my tsconfig.json, I made sure that removeComments is set to false. I expect to see all the documentation for all the properties of the Direction object to carry over to the .d.ts file, however, I see the following output:

export default Direction;
/**
 * The direction enum.
 */
type Direction = number;
declare namespace Direction {
    const Up: number;
    const Down: number;
    const Left: number;
    const Right: number;
}

You can try it for yourself on the TS Playground. How can I ensure that all the documentation properly carries over?

1 Answers

As a workaround, you could use both @typedef and @property tags.

I can't see why we'd add @readonly, though, since TypeScript constants already represent variables whose values cannot be modified and the Direction object literal, as it is currently defined, it's not truly readonly.

Take the definition below as an example:

/**
* @typedef Direction
* @property {number} Up "Up direction"  
* @property {number} Down "Down direction" 
* @property {number} Left "Left direction" 
* @property {number} Right "Right direction"
*/
const Direction = {
  Up: 1,
  Down: 2,
  Left: 3,
  Right: 4,
};
export default Direction;

Would generate the following .d.ts file:

export default Direction;
export type Direction = {
    /**
     * "Up direction"
     */
    Up: number;
    /**
     * "Down direction"
     */
    Down: number;
    /**
     * "Left direction"
     */
    Left: number;
    /**
     * "Right direction"
     */
    Right: number;
};
declare namespace Direction {
    const Up: number;
    const Down: number;
    const Left: number;
    const Right: number;
}

Would that work for your use case?

Cheers

Related