Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading