Install TypeScript declarations from npm

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

This lesson shows you how to acquire type declaration files for your TypeScript projects directly from npm.

[00:00] Here I have a simple TypeScript project. So far, it only consists of an empty TypeScript file, a package.json without any dependencies, and a default tsconfig.json. Open the terminal and install lodash by typing npm install lodash. Make sure to add the save flag to save the lodash package as a dependency.

[00:19] Now import the range function from lodash. You can use it like this to create a range of numbers. Notice the numbers variable is typed as any. This is because TypeScript doesn't know anything about the range function. There's no type information available here because lodash is written in JavaScript, not TypeScript.

[00:36] Give the type information by npm installing the type declaration package @types/lodash and make sure to save the package as a development dependency. All type declaration packages follow the naming convention @types/ and then the name of the package.

[00:51] Now that npm install has completed, check out the node_modules folder. You'll find two folders inside, one for lodash and one for all type declaration packages. By convention, the compiler will automatically pick up on all type declarations within the @types folder.

[01:05] Now that the type declarations are in place, TypeScript can tell us that numbers is of type number array. It also tells us about the range function -- for example, about all its parameter types, its return type, and the documentation.

[01:17] Finally, head over to the package.json file. You'll find entries for both lodash and its type declarations in here. This means you can treat a type declaration package like any other npm package and install it, restore it, or version it within package.json.