假设我具有定义一个类的此javascript代码。其静态方法之一返回一个用于实例化子级的类。
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注释。
我的问题是:记录一个类型(从@param
或@returns
开始)的类型的正确方法是什么?换句话说,如何记录上面代码中标记的@returns
?
jsdoc does not document用于表示扩展类的类型的任何特殊语法。
[一方面,您可能只使用ParentClass
作为类型(这意味着返回了该接口)—考虑到jsdoc实际上是一个文档工具,而不是严格的类型检查器(JavaScript方法更多)通常不只是期望一个特定的(可鸭式)接口,而不是强加instanceof
检查等。
但是,您可以使用@augments
标签(在jsdoc中也可以使用@augments
,并且在@extends
中也需要这样)来更精确地定义返回类型,例如:
Closure
((IIRC,尽管jsdoc并未按照闭包的要求记录使用带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);
}
};
}
}
的方括号,但我相信它可以与方括号一起使用。)
但是请注意,这仍然有些技巧,因为我们没有记录返回特定的instance,但是我们希望记录返回的整个类。有关未实现的问题,请参见@extends
。 (TypeScript允许https://github.com/jsdoc/jsdoc/issues/1349具有类型,例如typeof
。)