Installing Type Declaration Packages with 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:
- TypeScript 2.0: Non-Nullable Types
- TypeScript 2.0: Control Flow Based Type Analysis
- TypeScript 2.0: Acquiring Type Declaration Files
- TypeScript 2.0: Read-Only Properties
- TypeScript 2.0: Tagged Union Types
- TypeScript 2.0: More Literal Types
- TypeScript 2.0: The "never" Type
- TypeScript 2.0: Built-In Type Declarations
- TypeScript 2.1: async/await for ES3/ES5
- TypeScript 2.1: External Helpers Library
- TypeScript 2.1: Object Rest and Spread
- TypeScript 2.1: keyof and Lookup Types
- TypeScript 2.1: Mapped Types