JSDoc class fields type override

Viewed 66

Using JavaScript's latest class syntax, I have a class A, and it has a public field which is an Area object:

class Area {
   /** @type {number} */
   left;
   /** @type {number} */
   top;
   /** @type {number} */
   width;
   /** @type {number} */
   height;
}

class A {
   /** @type {Area} */
   area;
}

Now, I have a class Square extending class Area, and another class B extending class A. How can I state in JSDoc to re-define the type of B.area as a Square object, without re-declaring it?

class Square extends Area {
}

class B extends A {
   /** @type {Square} */
   area;  // <-- I want to remove this line of declaration, but to keep the new typing notation.
}
1 Answers

It's possible with @template and @extends. This would be the result:

class Area {
  /** @type {number} */
  left;
  /** @type {number} */
  top;
  /** @type {number} */
  width;
  /** @type {number} */
  height;
}

/**
 * @template {Area} T
 */
class A {
  /** @type {T} */
  area;
}

class Square extends Area {
}

/**
 * @extends {A<Square>}
 */
class B extends A {
}

enter image description here

Related