JSDoc:适用于孙辈的文档通用类型 类

JSDoc: document generic type that works for grandchildren classes

记录泛型类型适用于直接继承。但是当我有一个继承链时,没有办法让它为孙子们工作class。这是一个例子:

 * @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> 'fixes' 模板类型而不是将其传播到继承类型。例如,在

/**
 * @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;
  }
}