Ben*_*ers 8 javascript private jsdoc typescript .d.ts
假设我有一个 JavaScript 类
/**
* @element my-element
*/
export class MyElement extends HTMLElement {
publicMethod() {}
/** @private */
privateMethod() {}
}
customElements.define('my-element', MyElement);
Run Code Online (Sandbox Code Playgroud)
以及使用declaration和生成的声明文件allowJs:
export class MyElement extends HTMLElement {
publicMethod(): void;
/** @private */
privateMethod(): void
}
Run Code Online (Sandbox Code Playgroud)
我还在构建后脚本中将其连接到声明文件:
declare global { interface HTMLElementTagNameMap { 'my-element': MyElement; } }
Run Code Online (Sandbox Code Playgroud)
在打字稿文件中使用此元素时,我可以privateMethod在自动完成中访问。
import 'my-element'
const me = document.createElement("my-element")
me.// autocompletes `privateMethod`
Run Code Online (Sandbox Code Playgroud)
如何指示tsc将使用@privateJSDoc 标记注释的任何方法、字段或属性标记为私有?
根据 JSDoc 文档, using/** @private */是正确的语法,但这不是 TypeScript 处理它的方式。您需要利用 TypeScripts 语法来处理这个问题,它不能单独使用 JSDoc。
TypeScript 3.8 及更高版本支持 ES6 风格的私有字段。您可以使用#方法开头的符号来表示私有字段,如下所示:
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.
Run Code Online (Sandbox Code Playgroud)
或者,TypeScript 还允许您使用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'.
Run Code Online (Sandbox Code Playgroud)
这是使用 VS Code 智能感知的示例。
小智 -1
您需要@ignore对那些希望从文档中排除的方法和类使用注释。
@ignore 标记表示代码中的符号永远不应出现在文档中。
/**
* @class
* @ignore
*/
function Jacket() {
/** The jacket's color. */
this.color = null;
}
/**
* @namespace
* @ignore
*/
var Clothes = {
/**
* @class
* @ignore
*/
Jacket: function() {
/** The jacket's color. */
this.color = null;
}
};
Run Code Online (Sandbox Code Playgroud)
更多信息请参见: https: //jsdoc.app/tags-ignore.html
| 归档时间: |
|
| 查看次数: |
1305 次 |
| 最近记录: |