如何使用JSDoc类型脚本声明隐藏私有方法?

假设我有一个JavaScript类

/**
 * @element my-element
 */
export class MyElement extends HTMLElement {
  publicMethod() {}
  /** @private */
  privateMethod() {}
}

customElements.define('my-element', MyElement);

和一个声明文件,使用declarationallowJs生成:

export class MyElement extends HTMLElement {
  publicMethod(): void;
  /** @private */
  privateMethod(): void
}

我还在构建后脚本中将其连接到声明文件:

declare global { interface HTMLElementTagNameMap { 'my-element': MyElement; } }

在打字文件中使用此元素时,我可以访问自动完成中的privateMethod

import 'my-element'
const me = document.createElement("my-element")
me.// autocompletes `privateMethod`

如何指示tsc将使用@privateJSDoc标记批注的任何方法、字段或属性标记为私有?


解决方案

根据JSDoc文档,使用/** @private */是正确的语法,但这不是TypeScrip处理它的方式。您将需要利用类型脚本语法来处理此问题,它不能单独与JSDoc一起工作。

TypeScript 3.8 and up supports ES6 style private fields。您可以在方法的开头使用#符号表示私有字段,如下所示:

class Animal {
  #name: string;
  constructor(theName: string) {
    this.#name = theName;
  }
}

// example

new Animal("Cat").#name;
Property '#name' is not accessible outside class 'Animal' because it has a private identifier.
或者,TypeScript also allows you to declare a field as private使用private标记,并将提供所需的结果。这样做不会在自动完成过程中显示privateMethod(至少对我来说不会)。

/**
 * @element my-element
 */
class MyElement extends HTMLElement {
  publicMethod() {}
  /** @private */
  private privateMethod() {}
}

let element = new MyElement()

element.privateMethod()
// Error: Property 'privateMethod' is private and only accessible within class 'MyElement'.

这里有一个使用VS Code IntelliSense的示例。

相关文章