简体   繁体   中英

JSDoc: How do I let IntelliSense/TypeScript know about classes from other files?

I'm working on a relatively large project, and I want to add JSDoc to my classes and files to make it a lot easier to develop. I have a getter function for my "Configuration" class/object that returns its instance of a "SQLRegistry" object, which is set later on down the chain.

//configuration.js

/**
 * @returns {SQLRegistry} registry
 */
getRegistry() {
    return this._registry;
}
//sqlRegistry.js
const Configuration = require('./configuration');

class SQLRegistry {
    //other code
}

Unfortunately, in VS Code with IntelliSense/ESLint, it provides an error saying that it cannot find the class 'SQLRegistry'. In any other situation, I would just import sqlRegistry.js into configuration.js, but in this situation I cannot (because sqlRegistry depends on configuration.js, as you can see above).

TypeScript jsdoc 检查器给我一个错误,说它找不到名称“SQLRegistry”

Is there some sort of JSDoc comment I can put at the top of the file that tells it to read sqlRegistry.js, so that it becomes aware of the SQLRegistry class? For example, something like:

/**
 * @include {@link ./sqlRegistry.js}
 */

Your hypothetical @include {@link ./sqlRegistry.js} was very close in principal.

The actual way to write this under TypeScript's interpretation of JSDoc syntax is

/**
 * @returns {import('./sqlRegistry.js')} registry
 */
getRegistry() {
    return this._registry;
}

Note that it is TypeScript that actually powers the VS Code's primary JavaScript features like type inference, not ESLint

This syntax, import('module-specifier') in a type position, is known as import types , not to be confused with Type only imports and was introduced in TypeScript 2.9.

This is not a JSDoc specific feature but rather comes from TypeScript.

The TypeScript language service recognizes the syntax in JSDoc comment locations where a type is expected. Note that the official TypeScript Handbook states that

You can also import declarations from other files using import types. This syntax is TypeScript-specific and differs from the JSDoc standard:

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