简体   繁体   中英

How to reference class from another file as a param type?

I have a class that I want to reference as a jsdocs type in another file.

Something like this

// src/models/MyClass.js
/**
 * @class
 * @alias module:MyClass
 */
class MyClass {
  foo() {

  }
}

// src/controllers/index.js
/**
 * @param {*} context
 * @param {module:MyClass} context.myClass
 */
const myFunction = (context) => {
  const bar = context.MyClass()
  bar.foo()
}

I want to reference the myClass as a type as a param on myFunction but it keeps coming back as type any so it's ignoring the jsdocs param type.

How can I properly reference myClass as a param type?

You need to put the keyword export before the declaration of class myClass , so that you can import it in your other file.

By the way, I think that JSDoc is only a documentation tool, so your code is not affected by it.

This should be the way to do it. Just use @import to import a type from another file

// src/controllers/index.js
/**
 * @param {object} context
 * @param {typeof import('../models/MyClass').MyClass} context.MyClass
 */
const myFunction = (context) => {
  const bar = new context.MyClass()
  bar.foo()
}

PS: I'm assuming myFunction is some kind of a factory function that accepts the class as a parameter like below. That's why there is also a typeof in from of the import so you can pass the class itself.

myFunction(MyClass);

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