javascript - 如何用 JSDoc 记录扩展另一个类的类类型的参数?
问题描述
假设我有这个定义一个类的 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 注释。
我的问题是:记录从另一个类扩展的类(在 a@param
或中)的正确方法是什么?@returns
换句话说,我如何记录@returns
上面代码中的标记?
解决方案
jsdoc没有记录任何表示扩展类的类型的特殊语法。
一方面,您可能只使用ParentClass
as 类型(暗示这个接口就是返回的内容)——考虑到 jsdoc 实际上是一个文档工具而不是一个严格的类型检查器(并且 JavaScript 方法比预期的更常见)一个特定的(鸭子类型的)接口,而不是强加instanceof
检查等)。
@augments
但是,您可以使用标记(在 jsdoc 中也可以使用,并且在Closure@extends
中也需要这样)来提供更精确的返回类型定义:
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}
.)
推荐阅读
- node.js - 将 socketio 套接字 id 转换为套接字对象
- .net - 如何在 CDK 应用程序中获取 RDS 实例主机名?
- python - 使用 cftime 日期在 xarray 线图中设置 xticks
- android - 以 android (HaxeDevelop) 为目标时如何解决此构建错误?
- javascript - 如何调整画布的大小?
- java - 如何将 foreach 变成 lambda?
- c# - how to rollback all SqlCommands which already executed with SqlTransaction?
- azure - 使用复制对象创建多个 Azure VM
- javascript - 如何在 JavaScript/TypeScript 中将字符串转换为 Long(不长)
- linux - 更改 IP 后 RIAK 节点不启动