从 JavaScript 生成 TypeScript 定义时如何生成枚举成员的文档?

Sam*_*her 5 javascript jsdoc typescript

按照从 .js 文件创建 .d.ts 文件中的官方说明,我尝试生成 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;

Run Code Online (Sandbox Code Playgroud)

对于我来说tsconfig.json,我确保removeComments设置为false. 我希望看到Direction对象的所有属性的所有文档以保留到.d.ts文件中,但是,我看到以下输出:

export default Direction;
/**
 * The direction enum.
 */
type Direction = number;
declare namespace Direction {
    const Up: number;
    const Down: number;
    const Left: number;
    const Right: number;
}
Run Code Online (Sandbox Code Playgroud)

您可以在TS Playground上亲自尝试一下。如何确保所有文档正确延续?

Moa*_*Moa 1

作为解决方法,您可以同时使用@typedef@property标签。

不过,我不明白为什么我们要添加@readonly,因为 TypeScript 常量已经代表了其值无法修改的变量Direction,而对象字面量(如当前定义的那样)并不是真正的readonly

以下面的定义为例:

/**
* @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;
Run Code Online (Sandbox Code Playgroud)

将生成以下.d.ts文件:

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;
}
Run Code Online (Sandbox Code Playgroud)

这对您的用例有用吗?

干杯