node.js - JSDoc:适用于孙子类的文档泛型类型
问题描述
记录泛型类型适用于直接继承。但是当我有一个继承链时,没有办法让它为孙子类工作。这是一个例子:
* @property {string} color
* @template {T}
*/
class MyColor {
constructor() {
this.color = 'unknown';
}
/**
* @returns {T}
*/
static makeColor() {
return /**@type {T}*/ new this.prototype.constructor();
}
}
/**
* @extends MyColor<Red>
* @template {T}
*/
class Red extends MyColor {
constructor() {
super();
this.color = 'red';
}
}
/**
* @extends Red<DarkRed>
*/
class DarkRed extends Red {
constructor() {
super();
this.level = 2;
}
darker() {
this.level += 1;
}
}
const circle = DarkRed.makeColor();
DarkRed.makeColor
仅将 return 识别为Red
,但不是DarkRed
。有没有办法让它工作@template
?或者有没有其他方法可以让它工作?
我使用 WebStorm 作为 IDE。
解决方案
从https://github.com/google/closure-compiler/wiki/Generic-Types#inheritance-of-generic-types,@extends MyColor<Red>
“修复”模板类型,而不是将其传播到继承类型。例如,在
/**
* @constructor
* @template T
*/
var A = function() { };
/** @param {T} t */
A.prototype.method = function(t) { };
/**
* @constructor
* @extends {A<string>}
*/
var B = function() { };
/**
* @constructor
*
* @extends {B<number>}
*/
var C = function() { };
var cc =new C();
var bb = new B();
var bm = bb.method("hello");
var cm = cc.method(1);
cc.method(1)
将导致TYPE_MISMATCH: actual parameter 1 of A.prototype.method does not match formal parameter
found : number
required: string
您可以尝试将代码更改为
/**
* @property {string} color
* @template {T}
*/
class MyColor {
constructor() {
this.color = 'unknown';
}
/**
* @returns {T}
*/
static makeColor() {
return /**@type {T}*/ new this.prototype.constructor();
}
}
/**
* @extends MyColor<T>
* @template {T}
*/
class Red extends MyColor {
constructor() {
super();
this.color = 'red';
}
}
const circle1 = Red.makeColor();
/**
* @extends Red<DarkRed>
*
*/
class DarkRed extends Red {
constructor() {
super();
this.level = 2;
}
darker() {
this.level += 1;
}
}
const circle = DarkRed.makeColor();
另一种可能的解决方案是使用@return {this}
代替@template
(自 2018.2 起工作):
class MyColor {
constructor() {
this.color = 'unknown';
}
/**
* @return {this}
*/
static makeColor() {
return new this.prototype.constructor();
}
}
class Red extends MyColor {
constructor() {
super();
this.color = 'red';
}
}
class DarkRed extends Red {
constructor() {
super();
this.level = 2;
}
darker() {
this.level += 1;
}
}
推荐阅读
- node.js - 节点/角度 CORS 问题
- wpf - 我可以同时拥有代码隐藏 Click 事件和命令吗?
- javascript - Npm 和节点导入
- elixir - 是否可以将 Ueberauth 配置为使用 Github Enterprise 登录?
- python-3.x - 涡轮增压 lambda 函数比较两个数据帧中的值
- javascript - 即使客户端没有提供回调,有没有办法从服务器发送响应?
- javascript - 在下拉菜单上使用锚标记进行页面导航
- javascript - 有没有办法创建一个可以读取它所在目录的模块?(打字稿/JavaScript)
- java - 在静态成员类中展平 JUnit 测试
- ios - 如何在 SwiftUI 中迭代/foreach 数组