有没有办法在 TypeScript 的接口中记录字段?

ffx*_*sam 14 intellisense typescript visual-studio-code

说我有以下几点:

interface Validator {
  validate: (value: string) => boolean;
  errorMessage: string;
}

interface EditDialogField {
  label: string;
  prop: string;
  required?: boolean;
  type: 'input';
  validators?: Validator[];
}
Run Code Online (Sandbox Code Playgroud)

这很有用,因为当我使用这些界面时 IntelliSense 会弹出建议,但我希望能够添加也显示在 IntelliSense 中的注释(特别是 VS Code)。这可能吗?

ffx*_*sam 30

知道了!

interface EditDialogField {
  /** Explain label here */
  label: string;
  /** Explain prop here */
  prop: string;
  required?: boolean;
  type: 'input';
  validators?: Validator[];
}
Run Code Online (Sandbox Code Playgroud)

  • 可以确认这在 VSCode 中有效,但在 https://tsdoc.org 上找不到它的记录 (2认同)

Ron*_*ere 13

如果您想在鼠标悬停在编辑器中时看到它出现,我建议您记录界面并使用@field内部文档注释。

或者,您可以使用@member它为文档提供更好的语法突出显示

/**
 * This is the description of the interface
 *
 * @interface EditDialogField
 * @member {string} label is used for whatever reason
 * @field {string} prop is used for other reason
 */
interface EditDialogField {
  label: string;
  prop: string;
  required?: boolean;
  type: 'input';
  validators?: Validator[];
}
Run Code Online (Sandbox Code Playgroud)

VSCode 中的结果 在此处输入图片说明


kir*_*ril 5

我想以@Ronan Quillevere@ffxsam的答案为基础。

Ronan 的方法将鼠标悬停在界面上时在 VSCode 中显示信息,如他的评论中所示。

但是,当使用该界面(如下例所示)时,将鼠标悬停在最后一行的解构变量上不会显示成员/字段标记的文档,而是显示界面内注释的文档,如 ffxsam 建议的那样。

/**
 * This is the description of the interface
 *
 * @interface EditDialogField
 * @member {string} label is used for whatever reason
 * @field {string} prop is used for other reason
 */
 interface EditDialogField {
  /** Doc inside the interface */ 
  label: string;
  prop: string;
  required?: boolean;
  type: 'input';
}

const dialog: EditDialogField = { label: 'label', prop: 'prop', type: 'input' };
const { label, prop } = dialog;
Run Code Online (Sandbox Code Playgroud)

这些图片更好地展示了 VSCode 中的行为。 在此输入图像描述

在此输入图像描述

我不确定是否有办法统一这一点,但这会很棒