Sub topic 10
Add types for third-party packages
This chapter assumes you have a working tsconfig.json and have renamed at least one file to .ts. You should also know how import resolves packages from node_modules and what noImplicitAny does. After the rename, the compiler starts asking what types your dependencies have. This chapter shows how to answer that question for every package you use.
Where a package's types come from
TypeScript checks your code against type declarations. A declaration file ends in .d.ts and describes a module's shape without containing any runtime code. A package can get its declarations in three ways.
| Situation | How to recognize it | What to do |
|---|---|---|
| The package ships its own types | `package.json` has a `types` or `typings` field, or an `index.d.ts` file | Nothing. Import it. |
| Types live in DefinitelyTyped | A package named `@types/<name>` exists on npm | Install it as a dev dependency. |
| No types exist | The compiler reports TS7016 | Write a small declaration file yourself. |
DefinitelyTyped is a community repository that publishes type declarations for packages that don't include their own. Its packages all live under the @types scope on npm.
Check whether a package already has types
Before you install anything, look at the package itself. The npm registry reports the types field directly:
npm view axios typesIf this prints a path such as index.d.ts, the package ships its types. If it prints nothing, check node_modules/<name>/package.json and look for index.d.ts in the package folder. Many packages ship types without a types field, because TypeScript falls back to an index.d.ts next to the entry file.
Installing an @types package for a library that already ships types is unnecessary. It can also cause conflicts, because the two sets of declarations may disagree.
Install types from DefinitelyTyped
When a package has no types of its own, search npm for @types/<name>. Install it as a dev dependency, because the declarations only matter at compile time:
npm install --save-dev @types/express @types/lodashYou don't change your imports. TypeScript finds node_modules/@types/express automatically when you write import express from "express".
import express from "express";
const app = express();
app.get("/users/:id", (req, res) => {
res.json({ id: req.params.id });
});
app.listen(3000);Here req and res get their types from @types/express. Hovering over req.params.id in your editor shows string. A misspelling such as res.jsno(...) is now a compile error instead of a runtime crash.
Some packages need the types package for your runtime too. The setup chapter already added @types/node, which types built-in modules such as fs and path, along with globals like process.
Match the version
The version of @types/x should line up with the major and minor version of x. DefinitelyTyped versions follow the library: @types/[email protected] describes Express 4.17. When you upgrade a library, upgrade its @types package too. A mismatch produces confusing errors about methods that exist at runtime but not in the types, or the reverse.
Read the TS7016 error
Suppose you import a package that has neither its own types nor an @types entry:
import slugify from "legacy-slugify";With noImplicitAny on, the compiler reports:
error TS7016: Could not find a declaration file for module 'legacy-slugify'.
'/project/node_modules/legacy-slugify/index.js' implicitly has an 'any' type.The message names the exact JavaScript file it found and tells you the module is typed as any. It also suggests two fixes: installing @types/legacy-slugify if one exists, or adding a declare module statement.
The error is silent when strict is off
Your starter tsconfig.json sets "strict": false. With noImplicitAny off, TS7016 doesn't appear. The import quietly becomes any, and so does every value that comes out of it. The code compiles, but those calls have no checking at all.
Write your own declaration
When no types exist anywhere, you have two options: a quick shorthand or a real declaration.
Shorthand: accept any
Create src/types/legacy-slugify.d.ts with one line:
declare module "legacy-slugify";This silences the error. Everything imported from the module is any, so it gives you the same safety as before, only without the error message. Use it as a placeholder to unblock the migration.
A real declaration
Describe only what your code uses. You don't need the whole API. The following file types a function that takes a string and an options object, and returns a string:
declare module "legacy-slugify" {
export interface SlugifyOptions {
lower?: boolean;
separator?: string;
}
export default function slugify(
text: string,
options?: SlugifyOptions
): string;
}Now the call below is checked. The compiler knows the result is a string and rejects a numeric text:
import slugify from "legacy-slugify";
const slug: string = slugify("Hello World", { lower: true, separator: "-" });
console.log(slug);Two rules keep this file working:
- Keep the declaration file free of top-level
importorexportstatements. A.d.tsfile with a top-level import becomes a module, and thendeclare module "x"is read as an augmentation of an existing module instead of a new declaration. Put any imports inside thedeclare moduleblock. - Make sure the file is included. Your
includesetting of["src"]already coverssrc/types. If you put declarations elsewhere, add that folder toinclude.
Match the module's export style
The declaration must describe how the package actually exports. A CommonJS package that does module.exports = function () {} is declared with export =:
declare module "old-style-pkg" {
function run(input: string): number;
export = run;
}You then import it with import run from "old-style-pkg" when esModuleInterop is on, which is why the starter config enables it. Without that option, you would write import run = require("old-style-pkg"). If a default import gives you undefined at runtime, the export style in your declaration is the first thing to check.
Compiler options that affect type lookup
Two options in tsconfig.json change which declarations the compiler loads.
typesrestricts which@typespackages are loaded as global declarations. If you set"types": ["node"], then only@types/nodeis included automatically, and globals from@types/jestdisappear. Imports likeimport express from "express"still work, because explicit imports are always resolved. If test globals such asdescribesuddenly become unknown, an overly narrowtypeslist is a likely cause.skipLibCheckskips type checking of all.d.tsfiles. It's on in the starter config. It hides errors inside declaration files you don't control, but it doesn't hide errors in your own code that uses them.
Verify the result
Run the compiler without producing output to see every remaining error:
npx tsc --noEmitFix errors from the top. A single missing @types package often explains many errors further down, because every value flowing out of that import was affected.
Common mistakes
- Installing
@types/xas a regular dependency. Use--save-dev, since declarations aren't needed at runtime. - Forgetting that
@typespackages are separate from the library, so a library upgrade can leave the declarations out of date. - Declaring a module inside a file with a top-level
import, which turns it into an augmentation. - Leaving
declare module "x";in place forever. Treat it as a to-do item.
Exercise
You import left-pad-ish in a .ts file. With "noImplicitAny": true, tsc reports TS7016 for it. npm view left-pad-ish types prints nothing, and npm search @types/left-pad-ish finds nothing. Your function call is pad("7", 3) and it returns a string. What do you add, and where?
Show answer
Create a declaration file such as src/types/left-pad-ish.d.ts, with no top-level import or export, containing declare module "left-pad-ish" { export default function pad(text: string, length: number): string; }. The file sits under src, so include picks it up. Run npx tsc --noEmit to confirm TS7016 is gone. A temporary shorthand declare module "left-pad-ish"; would also silence the error, but it types everything as any.