Installing Type Declaration Packages from npm
Let's assume you want to use Lodash in one of your TypeScript projects:
npm install --save lodash
After running this command, Lodash is installed into the
node_modules folder and is also listed as a dependency within your project's
Using npm again, you can now install the
@types/lodash package which contains the corresponding type declarations that TypeScript needs:
Note how the type declaration package is named after the original npm package, prefixed with
@types/. Most packages should follow this convention, but you can always fall back to TypeSearch to find the name of the type declaration package for a given library.
The benefit of using npm for managing type information is that type declaration packages will be listed in your
package.json alongside your other dependencies. In addition, they can be properly versioned, just like any other npm package. Plus, you only need a single package manager, npm, that is set up already anyway.
Where Do the Type Declaration Files Go?
Like any other npm package, the type declaration packages are installed in the
node_modules folder. Within it, there's a
@types folder which contains all typings. In the above example, it'll contain a
lodash folder, within which you'll find the
index.d.ts file with all the Lodash type information:
The TypeScript compiler understands this convention and will pick up type declarations within the
@types folder automatically. There's no need to update the
tsconfig.json or any other configuration file.
Who Creates the Type Declaration Packages?
Behind the scenes, the type declaration packages are automatically created by the types-publisher service. It publishes the contents of the DefinitelyTyped repository to npm. That way, typings contributed to DefinitelyTyped end up on npm, ready for consumption.
This post is part of the TypeScript Evolution series.