How can I hide #39;private#39; methods with JSDoc Typescript Declarations?(如何使用JSDoc类型脚本声明隐藏私有方法?)
问题描述
假设我有一个JavaScript类
/**
* @element my-element
*/
export class MyElement extends HTMLElement {
publicMethod() {}
/** @private */
privateMethod() {}
}
customElements.define('my-element', MyElement);
和一个声明文件,使用declaration和allowJs生成:
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类型脚本声明隐藏私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用JSDoc类型脚本声明隐藏私有方法?
基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
