Reputation: 2638
Using JSDoc, is it possible to let a base class know about a param type defined in a derived class in javascript?
For example:
class ServiceBase {
constructor(repository) {
this.repository = repository;
}
}
class MyRepository {
someFunction() {}
}
class MyService extends ServiceBase {
/**
* @param {MyRepository} repository
*/
constructor(repository) {
super(repository);
}
doWork() {
// JSDoc doesnt know about this this.repository.someFunction,
// because it doesnt know the type of this.repostory
this.repository.someFunction();
}
}
The main thing I'm looking for is intellisense in VSCode, but since the repository
instance type is not known by the MyService
class, I cannot get prompts for functions etc.
I think I already know the answer is "no", but figure it's worth checking if anyone knows how to achieve this kind of thing.
Upvotes: 1
Views: 703
Reputation: 10379
Use @template
to create a generic ServiceBase
, add @extends
to MyService
and annotate MyService
's constructor parameter type with @param
. It's going to be like:
/**
* @template T
*/
class ServiceBase {
/**
* @param {T} repository
*/
constructor(repository) {
this.repository = repository;
}
}
class MyRepository {
someFunction() {}
}
/**
* @extends ServiceBase<MyRepository>
*/
class MyService extends ServiceBase {
/**
* @param {MyRepository} repository
*/
constructor(repository) {
super(repository);
}
doWork() {
this.repository.someFunction();
}
}
Upvotes: 1