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.
Asked
Active
Viewed 1.2k times
2 Answers
36
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:

customcommander
- 17,580
- 5
- 58
- 84
-
There was in issued for this https://github.com/microsoft/TypeScript/issues/25386. It was closed but I don't think they fixed it. – Qiulang Dec 05 '20 at 04:08
-
This works perfectly for my project and does not require use of "includes" – GaryBishop Oct 14 '21 at 19:37
15
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.

zavr
- 2,049
- 2
- 18
- 28
-
2If you do this in a lot of files, you'll end up with a big list of `Context` typedefs. Every time you try to import `Context`, autocomplete will show this list and it's not clear which one to pick :( – Jespertheend Sep 30 '21 at 09:03
-
@Jespertheend True, but how is that different from importing code? In the end, the path to `Context` determines which one we mean. Alternatively you would have to use unique names for your various `Context` types. I believe the alternative is more cumbersome. – pipereset Jul 06 '22 at 14:22
-
1The difference is that when you import code it doesn't get exported automatically. I don't think there's any good way to work around this at the moment. There's an open ticket for this here: https://github.com/microsoft/TypeScript/issues/46011 – Jespertheend Jul 06 '22 at 15:03