Using @types packages
In this page:
What @types Packages Are
@types packages are community-maintained declaration files published separately on npm for JavaScript libraries that don't ship their own TypeScript types, hosted collectively under the DefinitelyTyped project.
Example: What @types Packages Are
// npm install --save-dev @types/lodash
// Provides types for the lodash JS library, published under DefinitelyTyped.
console.log("@types packages add compile-time types for untyped JS libraries");
Installing a Type Package
Installing a type package (like npm install --save-dev @types/lodash) adds nothing to your runtime bundle — it only adds compile-time type information that TypeScript picks up automatically alongside the library it types.
Example: Installing a Type Package
// npm install --save-dev @types/express
// Adds zero runtime code -- only type information used by the compiler.
console.log("Installing @types/express adds no runtime bundle weight");
Using Typed Library APIs
Once a @types package is installed, calling into that library's functions gets full autocomplete and type-checking as if the library had been written in TypeScript from the start, catching mismatched arguments before you run anything.
Example: Using Typed Library APIs
// After installing @types/lodash:
// import _ from "lodash";
// _.chunk([1, 2, 3], 2); // fully typed and autocompleted
console.log("Typed library calls get full autocomplete and checking");
Libraries with Built-In Types
Some libraries ship their own types bundled directly in their package (often noted by a types or typings field in their package.json), which means installing a separate @types package for them isn't necessary or even possible.
Example: Libraries with Built-In Types
// axios ships its own types (see its package.json "types" field),
// so `npm install --save-dev @types/axios` is unnecessary.
console.log("Some libraries bundle their own types, skip a separate @types install");
Checking Type Package Availability
Before assuming you need a separate @types install, check the library's own package for bundled types first — installing a redundant @types package for an already-typed library can create conflicting type definitions.
Example: Checking Type Package Availability
// Check package.json for a "types" or "typings" field first.
// Installing a redundant @types package can create conflicting definitions.
console.log("Always check for bundled types before installing @types separately");
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: