How to use d.ts file for intellisense in VS Code similar to NPM approach

Viewed 2231

I have a nodejs project (in JS). Unfortunately, I have to utilize a lot of node global variables.

Everything works fine (even a lot of people are suggesting not to use globals) except thing:

There is no intellisense for globals. So every time I want to use, let's say, global function/object I need to look in its code and figure out what are the parameters, what does it return, etc.

Let's say I have a global variable which is a pure object:

foo = {
    bar: {
        level2: {
            level3: {
                level4: "abc
            }
        }
    }
}

It's quite annoying to deal with it since I can't "see" the structure of the object when using it and it's easy to make a mistake when writing code.

The reason why I posted this question is the ...npm packages

There are plenty of packages written in vanilla JS and most of them are utilizing the power d.ts files. Once you install the package you can use it from any place in your projects and VS code will have intellisense for them. If you will click on tooltip (IDK how it's called... Type definition tooltip?) of VS code you will be navigated to the d.ts file of the package (not the actual implementation of the command).

So my question is how to do the same in my project. I'm not going to publish it as npm I just want a d.ts file somewhere in the project so I can use my global without looking into its implementation every time I need to recall what it does.

2 Answers

Let inside your .d.ts file be anything

To access variables, functions, interface add this line in your .ts file, VS code IntelliSense will suggest you

/// <reference path="./test.d.ts" />

If you want to use this test.d.ts all over your project not just on any particular file. Then add this line in tsconfig.json

"files" : [ "./src/test.d.ts" ]

Update as mentioned in the comment section

my js file which I am assuming similar to what you are trying to do

export const testString = 'aditya';

in your js file you

/// <reference path="test.js" />

Regardless of if it is possible or not, the worst drawback of what you are looking for is that the declaration file(s) must be kept updated by hand each time a global variable/function is changed.

There are plenty of packages written in vanilla JS and most of them are utilizing the power d.ts files.

Usually .d.ts files are not written by hand, but are produced by tsc: many of the packages you are speaking about are probably written in TypeScript and distributed as JavaScript packages (to be used in JavaScript projects as well) with an associated index.d.ts file (to be used in TypeScript projects)

even a lot of people are suggesting not to use globals

+1

Related