Lesson

TypeScript Definitely Typed

10 min reading
Free Course

TypeScript Definitely Typed: Adding @types/* to JS Libraries

Many popular npm packages were originally written in plain JavaScript without TypeScript source files. DefinitelyTyped is the community repository that publishes type declaration packages under the @types/ scope so TypeScript understands those libraries cleanly.

When you install a JavaScript package like lodash or express, installing its companion @types/lodash or @types/express unlocks full autocomplete and compile-time checks.

Installing @types/* Packages

Always install @types/* packages as devDependencies (-D) because type declarations are stripped during compilation and never needed in production runtime.

npm install express
npm install -D @types/express

TypeScript automatically discovers packages inside node_modules/@types unless you override typeRoots in tsconfig.json. Note that packages already written in TypeScript (like axios, zod, or prisma) ship their own .d.ts files—do not install duplicate @types/ stubs for them.

Writing a Custom .d.ts Declaration File

If a niche JavaScript library lacks an @types/* package, create a local src/types/untyped-pkg.d.ts file to declare its module shape:

declare module "legacy-slugify" {
  export default function slugify(input: string, separator?: string): string;
}

Common Mistakes to Avoid

  • Installing @types/* under dependencies instead of devDependencies: Type packages belong in devDependencies (npm i -D).
  • Installing mismatched major versions: Keep @types/react matched to your installed react major version (v18 with v18, v19 with v19) to avoid confusing JSX errors.
  • Adding declare module "*" globally: Silencing all missing module checks hides genuine misspelled import paths.

Frequently Asked Questions

What is a .d.ts declaration file?

A .d.ts file contains only TypeScript type signatures (declare function, interface, type) with zero runtime implementation code.

How do I know if a package already includes built-in types?

Check the package's package.json for "types" or "typings" fields (or look for the TS badge on npmjs.com).

Can I generate .d.ts files for my own library?

Yes. Set "declaration": true in tsconfig.json so tsc emits .d.ts files alongside your .js output.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum