1

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?

starball
  • 20,030
  • 7
  • 43
  • 238
Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
  • 1
    add JSDOC to the constructor to tell it the types of the parameters, you will have to import the Employer class – rioV8 May 05 '23 at 03:38
  • @rioV8 this seems like a legit solution. Although that will generate linter error of not used import. Any way to avoid this? Like soft referencing to the file? – Teoman shipahi May 05 '23 at 03:41
  • why does the `Employer` have a name, but the `Employee` not – rioV8 May 05 '23 at 03:42
  • 1
    where does the employer name even come from? You don't pass one in the constructor call. – starball May 05 '23 at 03:43
  • This is just a demonstration. Real files are totally different, but conceptually I am having the same problem. @rioV8 – Teoman shipahi May 05 '23 at 03:43
  • then learn the linter to read JSDOC, you use the name property, so you need to have the `Employer` class to have the linter happy, it must know that `this.employer` has a `name` property, it should complain about that if not imported – rioV8 May 05 '23 at 03:46

1 Answers1

1

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

starball
  • 20,030
  • 7
  • 43
  • 238