如何使用JSDoc类型脚本声明隐藏私有方法? [英] How can I hide 'private' methods with JSDoc Typescript Declarations?

查看:50
本文介绍了如何使用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的示例。

这篇关于如何使用JSDoc类型脚本声明隐藏私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆