Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to type in different file in JSDoc without importing

I'm writing JavaScript (ES6) code in Visual Studio Code and enabled VSCode's type checking as explained in the VSCode docs.

When referring to a type that is defined in another file (Track in the example below), I get an error like [js] Cannot find name 'Track' at the JSDoc reference to that type unless I import it. When I import this type, I get an error from ESLint: [eslint] 'Track' is defined but never used. (no-unused-vars)

I don't want to disable the ESLint rule. Is there a way to import the type only for the type checks in VSCode?

import Track from "./Track";

export default class TrackList {

/**
 * Creates a new track list.
 * @param {Iterable<Track>} tracks the tracks to include
 */
constructor(tracks) {
    this._tracks = tracks ? Array.from(tracks) : [];
}
...
like image 706
ralfstx Avatar asked Dec 26 '17 10:12

ralfstx


People also ask

Does JSDoc work with TypeScript?

You can use most JSDoc type syntax and any TypeScript syntax, from the most basic like string to the most advanced, like conditional types.

What is Typedef in JS?

The @typedef tag is useful for documenting custom types, particularly if you wish to refer to them repeatedly. These types can then be used within other tags expecting a type, such as @type or @param. Use the @callback tag to document the type of callback functions.

How do I view a JSDoc file?

Press Ctrl+Shift+O for viewing all the methods and corresponding JSDoc opens up when you select a method there and hover over the method.


2 Answers

I have a similar problem and here is how I solved it.

//file.d.ts
export interface Foo {
    bar: number;
}

export as namespace Baz;

Doing this will make the Baz namespace global so you can use it anywhere without importing

/**
 * @param {Baz.Foo} arg 
 */
function test(arg) {

}

Now you get intellisense and type checking in VSCode.
VS Code

like image 58
Jeremy Avatar answered Sep 22 '22 11:09

Jeremy


Just to keep this topic updated:

With [email protected] you will be able to import JSDoc typedefs, that are automatically exported.

Take a look at this issue with a real working example. Also you can walk along webpack's code to see how they used JSDoc and typescript ti statically chech their pure JS sourcecode base. here is their issue with JSDoc conventions where you can get insipration.

like image 28
Sergio Avatar answered Sep 24 '22 11:09

Sergio