How can I make a VS Code reference from one class to another class file while it is injected through a constructor?

Advertisements

I have three files:

  • index.js
  • employee.js
  • employer.js

index.js

import Employer from "./employer.js"
import Employee from "./employee.js"

const employer = new Employer();
const employee = new Employee(employer);

employee.js

class Employee {
  constructor(employer) {
    this.employer = employer;
  }

  getEmployer() {
    return this.employer.name();
  }
}

employer.js

class Employer() {
  name() {
   return "Default Employer";  
  }
}

The problem here in VS code is that if I CTRL + Click on the employer.name() it does not navigate to employer.js file since it is not referenced via "import" but passed via constructor parameter. Since I am in a vanilla JS environment, is there a way to tell VS Code that employer is an instance of “Employer” class and make it navigate when I click on it?

>Solution :

Here’s a solution using JSDoc, but it requires you to turn your employer.js into a ES6 module:

employer.js example:

export class Employer() {
  name() {
    return "Default Employer";  
  }
}

employee.js:

class Employee {
  /** @param {import("./employer").Employer} employer */
  constructor(employer) {
    this.employer = employer;
  }
  ...
}

The import() syntax is dynamic import syntax, which TypeScript supports type support for.

If you don’t want to have to turn employer.js into a ES6 module, see https://github.com/jsdoc/jsdoc/issues/1645 (also related: How to "import" a typedef from one file to another in JSDoc using Node.js?)

Leave a ReplyCancel reply