Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Install TypeScript declarations from npm


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



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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.

    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.

    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.

    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.

    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.