简体   繁体   中英

Javascript inheritance and JSDoc - let base class know about type defined in derived class

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.

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();
  }
}

截屏

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM