Use Type Definitions for Popular Projects on npm with @types

Share this video with your friends

Send Tweet

Not all projects on npm ship with their own Type definitions. For example, neither lodash or jquery include them. Thankfully, VS Code can automatically find and install type definitions for you or you can simply bring them in with npm i -D @types/lodash from the @types organization on npm.

Toni Lehtimaki
Toni Lehtimaki
~ 5 years ago

One more lesson could have been, that what to do when the library you want to use, does not have types available.

lolgrifon
lolgrifon
~ 2 years ago

npm i @types/<package-name>

Example: npm i @types/lodash npm i @types/jquery

And if it does not exist: While TypeScript is used to knowing everything about the code in your project, it doesn’t have to. In order to let you proceed, TypeScript just needs to know that your module exists.

And you do that through a declarations file.

In the root folder of your project, create a new file called decs.d.ts.

In this file, write:

declare module "my-untyped-module" So far, we’ve really just been following error messages. Now comes the part that the error messages leave out: making sure that TypeScript can find this file.

Include the declarations file In the root of your TypeScript project, you should have a tsconfig.json file. Open that up and find the property "include". This "include" array tells TypeScript where it should “look” for TypeScript files.

{ ... "include": [ "src" ] } You need to make sure that your decs.d.ts is included here.

You have two choices:

Move your decs.d.ts file into whatever folder you see in the "include" array. (In the example above, I’d move my file into my project’s src folder.) OR

Leave our decs.d.ts in the root of your project and add the file to the "include" array: { ... "include": [ "decs.d.ts" ] } Either choice will solve your error. You won’t have any types for the module (it’ll just be one big any) but you won’t have any errors, either.

Good luck!

(https://medium.com/@steveruiz/using-a-javascript-library-without-type-declarations-in-a-typescript-project-3643490015f3)