How to get VS Code to understand JSDOC's @typedef across multiple files

元气小坏坏 提交于 2019-12-05 17:51:32

问题


I want to specify a type in one file, and be able to reuse it in another one. I tried modules but it didn't work in VS Code. Is there any other solution? Just wanna have all types for my project to be reusable so I can reference them in different functions across files. This is the closest question I have found.


回答1:


I've had some success with using jsconfig.json and its include property in a plain JavaScript project in Visual Studio Code 1.33.1

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

Given the following JavaScript project:

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

Where both question.js and person.js are type definitions:

person.js

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

question.js

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

And answer.js is a function that accepts a question and return an answer:

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

As you can see in the first screencast I do get IntelliSense support when hovering over the Question type notation:

On top of that IntelliSense is also now able to offer code completion based on my types definitions:




回答2:


Since TypeScript 2.9 which is embedded in the newer VS Codes, it is possible by using the import syntax in JSDoc, like so

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

Also VS Code should be picking up all types defined across the workspace.



来源:https://stackoverflow.com/questions/45836847/how-to-get-vs-code-to-understand-jsdocs-typedef-across-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!