I've noticed a problem when working with a parent class that's extended by a child class. Both classes have a 'data' attribute, in the parent class it's a generic 'Object' type and in the child class it is of type 'DogData'.
The parent's constructor is setting 'this.data = data' which should override the type to whatever the child's attribute's type is, but this is not happening.
Please find a small reproducible example below:
I hope I'm missing something and please don't hesitate to point it out if I am.
Thanks in advance
* The animal base class
* @class
*/
class Animal {
/**
* @param {number} id The ID of the animal
* @param {Object} data The data of the animal
*/
constructor (id, data) {
this.id = id
this.data = data
}
}
/**
* The Dog class
* @class
* @extends Animal
*/
class Dog extends Animal {
/**
* @typedef DogData
* @property {number} age
* @property {string} name
*/
/**
* @param {number} id The ID of the dog
* @param {DogData} data The data of the dog
*/
constructor (id, data) {
super(id, data)
}
}
const dog = new Dog(1, { age: 10, name: 'Foobar' })
dog.data. // Will only autocomplete if this.data is explicitly set inside the Dog constructor
Define the property before the constructor and use @type on it.
class Dog extends Animal {
/**
* @typedef DogData
* @property {number} age
* @property {string} name
*/
/**
* @type {DogData}
*/
data;
/**
* @param {number} id The ID of the dog
* @param {DogData} data The data of the dog
*/
constructor (id, data) {
super(id, data)
}
}