如何让VS Code了解JSDOC跨多个文件的@typedef

问题描述 投票:12回答:2

我想在一个文件中指定一个类型,并能够在另一个文件中重用它。我尝试了modules,但它在VS Code中无效。还有其他解决方案吗?我想让我的项目的所有类型都可以重用,这样我就可以跨文件在不同的函数中引用它们。 This is the closest question我找到了。

visual-studio-code jsdoc
2个回答
3
投票

嵌入在较新的VS代码中的Since TypeScript 2.9,可以在JSDoc中使用import语法,就像这样

/**
 * @typedef {import("koa").Context} Context
 *
 * @typedef {Object} BodyparserOptions
 * @prop {(ctx: Context) => boolean} [detectJSON] Custom json request detect function. Default `null`.
 */

此外,VS Code应该拾取工作区中定义的所有类型。


2
投票

我在Visual Studio Code 1.33.1中的一个普通JavaScript项目中使用jsconfig.json及其include属性取得了一些成功。

{
  "include": [
    "src/**/*.js"
  ]
}

给出以下JavaScript项目:

src/
├── types/
|   ├── person.js
|   ├── question.js
|
├── answer.js
├── jsconfig.json

question.jsperson.js都是类型定义:

person.js

/**
 * @typedef {object} Person
 * @property {string} firstName
 * @property {string} lastName
 */

question.js

/**
 * @typedef {object} Question
 * @property {Person} askedBy
 * @property {string} text
 */

answer.js是一个接受问题并返回答案的函数:

/**
 * Takes a question and return an answer
 * @param {Question} question 
 */
function answer(question) {
  return 42;
}

正如您在第一次截屏视频中看到的,当我将鼠标悬停在Question类型表示法上时,我会获得IntelliSense支持:

enter image description here

最重要的是,IntelliSense现在还可以根据我的类型定义提供代码完成:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.