[英]How to document parameter of class type extending another class with JSDoc?
假设我有这个定义 class 的 javascript 代码。 它的 static 方法之一返回 class 用于实例化子级。
class ParentClass {
/**
* Creates an instance of parent class
*
* @param {string} type - the type of the instance.
*/
constructor(type) {
this.type = type;
}
/**
* Creates a child class.
*
* @param {string} type - the type.
*
* @returns {class<ParentClass> ?? ----- WHAT GOES HERE?? -----} the resulting class.
*/
static createChildClass(type) {
return class extends ParentClass {
constructor() {
super(type);
}
};
}
}
我正在使用 eslint 插件eslint-plugin-jsdoc
来检查代码中的 JSDoc 注释。
我的问题是:记录从另一个 class 延伸的 class 类型(在@param
或@returns
中)的正确方法是什么? 换句话说,我如何记录上面代码中标记的@returns
?
jsdoc没有记录任何用于表示扩展类的类型的特殊语法。
一方面,您可能只使用ParentClass
作为类型(暗示此接口是返回的内容)——考虑到 jsdoc 实际上是一个文档工具而不是严格的类型检查器(并且 JavaScript 方法通常不仅仅是期望一个特定的(duck-typable)接口,而不是强加instanceof
检查等)。
但是,您可以使用@augments
标记(在 jsdoc 中也可以作为@extends
,并且在Closure 中也是必需的)给出这样的返回类型的更精确定义:
class ParentClass {
// ...
/**
* Creates a child class.
*
* @param {string} type - the type.
*
* @returns {ChildClass} the resulting class.
*/
static createChildClass(type) {
/**
* @class ChildClass
* @augments ParentClass
*/
return class extends ParentClass {
constructor() {
super(type);
}
};
}
}
(IIRC,虽然 jsdoc 没有记录使用括号@extends
作为 Closure 显然需要,但我相信它可以与括号一起使用。)
请注意,这仍然是一个小技巧,但是,因为我们没有记录返回特定实例,但我们想要记录返回整个类。 有关未实现的问题,请参阅https://github.com/jsdoc/jsdoc/issues/1349 。 (TypeScript 允许typeof
带有类型,例如@returns {typeof ChildClass}
。)
如果您使用 Google Closure 类型语法(JSDoc 支持),您可以将 class 记录为构造函数 function 的类型(它确实在幕后)。
@param {function(new:SomeClass, arg1, arg2)}
有关更多详细信息,请参阅https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.