【问题标题】:How to refer in JsDoc (VS Code / IntelliSense) to class from another file without direct import?如何在 JsDoc(VS Code / IntelliSense)中引用另一个文件中的类而不直接导入?
【发布时间】:2023-04-10 01:20:01
【问题描述】:

问题

我使用 Visual Studio Code 并将 IntelliSense 与 JsDoc cmets 一起使用。 我有两个带有类声明的模块:

/**
 * This is Foo class 
 */
export default class Foo {
    constructor() {}
}

/**
 * This is Bar class 
 */
export default class Bar {
    constructor() {}

    /**
     * Init Bar from Foo
     * @param {Foo} foo instance of Foo
     * @returns {Bar}
     */
    static initFromFoo(foo) {
        return new Bar();
    }
}

Bar 类使用 Foo 作为方法 initFromFoo 的参数,但 IntelliSense 不理解 @param Foo 引用 class Foo 并且不能正常工作并说 foo:any

https://imgbbb.com/images/2019/09/24/image517c0ec9d1027ac9.png

如何让 IntelliSense 正常工作?

我尝试过的

  1. ./foo 导入./bar - 这可以使 IntelliSense 正常工作,但我不需要此导入,我只需要引用类型定义即可。
  2. 添加对另一个文件的引用,例如 TypeScript /// <reference path="./foo"> - 无效果
  3. 使用下一个内容创建jsconfig.json 文件:
{
    "compilerOptions": {
        "target": "es6",
        "allowSyntheticDefaultImports": true,
        "checkJs": true
    },
    "exclude": [
        "node_modules"
    ]
}

也没有影响。它只是突出显示错误Cannot find name 'Foo'.ts(2304)

P.S. 看起来像是与 ES6 模块相关的 IntelliSense 限制。因为如果我从两个文件中删除 export/import,IntelliSense 会按预期工作

https://i.ibb.co/CPL1gJC/image.png

https://i.ibb.co/xmXqzSk/image.png

P.S.S.抱歉,图片链接太少,无法发布图片。

【问题讨论】:

    标签: visual-studio-code intellisense es6-modules jsdoc javascript-intellisense


    【解决方案1】:

    可以通过import(path) 语句来导入类型。 例如:

    /**
     * Init Bar from Foo
     * @param {import('./foo').default} foo instance of Foo
     * @returns {Bar}
     */
    static initFromFoo(foo) {
        return new Bar();
    }
    

    /**
     * @typedef {import('./foo').default} Foo
     *
     * Init Bar from Foo
     * @param {Foo} foo instance of Foo
     * @returns {Bar}
     */
    static initFromFoo(foo) {
        return new Bar();
    }
    

    P.S. 它仅适用于 Visual Studio Code。它不是有效的 JsDoc。

    【讨论】:

      猜你喜欢
      • 2017-02-28
      • 2018-09-24
      • 2017-11-28
      • 2019-09-15
      • 1970-01-01
      • 2021-05-17
      • 2022-12-29
      • 2018-03-08
      • 2019-10-28
      相关资源
      最近更新 更多