Sub topic 11
Declaration files and @types packages
This chapter assumes you can run tsc with a tsconfig.json, that your project has a package.json, and that you know how import works in Node. Here you will learn what .d.ts files are, where the compiler finds them, and what to do when a JavaScript library has no types.
Why declaration files exist
The compiler type-checks your code, but many packages on npm are plain JavaScript. A .js file carries no type information that tsc can rely on. A declaration file (a file ending in .d.ts) describes the types of JavaScript code that exists somewhere else. It contains only declarations, never runnable code, and it produces no output when compiled.
Here is a declaration file for a hypothetical module math.js:
// math.d.ts
export declare function add(a: number, b: number): number;
export declare const VERSION: string;The word declare states that the thing exists at runtime and that only its type is described here. Without a function body, add could not be anything other than a declaration.
Declaration files are why you get autocomplete and error checking for libraries you did not write. Because types are erased at compile time, the declarations are used only while checking. They never reach the JavaScript output.
Where the types for an import come from
When you write import ... from "some-package", tsc has to find types for that package. There are three common sources:
- Bundled types. The package ships its own
.d.tsfiles and points to them with atypes(ortypings) field in itspackage.json, or with atypescondition inexports. Most modern packages do this. - An @types package. The community-maintained DefinitelyTyped repository publishes types for JavaScript-only packages under the
@typesscope on npm. For example,@types/lodashholds types forlodash. - Your own declarations. You write a
.d.tsfile in your project.
Installing an @types package
Install the JavaScript library as a normal dependency. Install its types as a development dependency, because types matter only while compiling:
npm install lodash
npm install --save-dev @types/lodashNow the import is fully typed:
import { chunk } from "lodash";
const groups = chunk([1, 2, 3, 4, 5], 2);
// groups is inferred as number[][]
console.log(groups);
chunk("not an array", 2); // error: string is not assignable to the expected list typeNaming follows a pattern. The types for express are in @types/express. For a scoped package such as @babel/core, the scope and name are joined with two underscores: @types/babel__core.
Some points about @types packages:
- Check whether the package already ships types before installing
@types/.... If it does, the extra package is unnecessary and can conflict with the bundled types. - Match versions loosely.
@types/nodehas a major version per Node.js release line, so use@types/node@22if you run Node 22. The major version should follow the Node version you target. - If you publish a library whose public types mention types from an
@typespackage, list that package underdependencies. Otherwise your users will not get the types.
Types for Node itself
Node's built-in modules and globals such as process, Buffer, and node:fs have no types in the compiler. They come from @types/node:
npm install --save-dev @types/nodeWithout it, you see errors like Cannot find name 'process' or Cannot find module 'node:fs'. Installing the package fixes both.
Writing your own declarations
If a package has no types anywhere, you have two choices. You can write a quick stub or write real declarations.
Put a file such as src/types/legacy-lib.d.ts in a folder covered by include. The key detail is that the file must have no top-level import or export. Otherwise TypeScript treats it as a module instead of an ambient (project-wide) declaration:
// src/types/legacy-lib.d.ts
declare module "legacy-lib" {
export function slugify(input: string): string;
export const defaultSeparator: string;
}Then use it as usual:
import { slugify } from "legacy-lib";
console.log(slugify("Hello World")); // stringDescribe only the parts of the API you actually use. You can add more later.
For a fast stub, a shorthand declaration marks every import from the module as type any:
// src/types/legacy-lib.d.ts
declare module "legacy-lib";How the compiler picks up .d.ts files
Your own .d.ts files are found through the same include setting that selects your source files. With "include": ["src"], any .d.ts under src is part of the program.
For packages in node_modules/@types, two options control which ones are loaded as global declarations:
| Option | Effect |
|---|---|
| `types` | A list of package names under `@types` to include globally. Only those are loaded. |
| `typeRoots` | Folders to look in instead of `node_modules/@types`. Rarely needed. |
Setting types is the clearest way to be explicit about which globals your project sees:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"types": ["node"]
},
"include": ["src"]
}Be aware of what types does and does not do. It limits which @types packages contribute global declarations, such as process from @types/node or describe from @types/jest. An explicit import of a package still resolves its types through normal module resolution.
skipLibCheck
"skipLibCheck": true, which appears in the tsconfig from earlier chapters, skips type-checking of all .d.ts files, including those in node_modules. It speeds up compilation and hides conflicts between two libraries' declarations. The trade-off is that mistakes in your own handwritten .d.ts files also go unreported. If you maintain a lot of declarations yourself, consider turning it off for a while to check them.
Generating declaration files for your own code
When you publish a library written in TypeScript, consumers need .d.ts files, because the compiled .js has no types. The declaration option makes tsc write them next to the JavaScript:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true
},
"include": ["src"]
}Given this source:
// src/index.ts
export function add(a: number, b: number): number {
return a + b;
}tsc produces dist/index.js and dist/index.d.ts. The second file looks like this:
export declare function add(a: number, b: number): number;declarationMap adds .d.ts.map files, so an editor's "go to definition" jumps to your .ts source instead of the .d.ts. Then point package.json at the declarations:
{
"name": "my-lib",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts"
}Two related options are worth knowing:
emitDeclarationOnlywrites only.d.tsfiles. Use it when a bundler or another tool produces the JavaScript.noEmitanddeclarationdo not combine usefully, becausenoEmitwrites nothing at all.
Common errors
| Message | Cause | Fix |
|---|---|---|
| TS7016: Could not find a declaration file for module 'x' | The package has no bundled types and no `@types/x` is installed. Appears under `strict` (through `noImplicitAny`). | Install `@types/x` if it exists, or add a `declare module "x"` file. |
| TS2307: Cannot find module 'x' or its corresponding type declarations | The package is not installed, the path is wrong, or `moduleResolution` does not match the package's layout. | Check the install and the import path. Verify `module` and `moduleResolution` in tsconfig. |
| Cannot find name 'process' | `@types/node` is missing, or it is excluded by `types`. | Install it and add `"node"` to `types` if you use that option. |
| Duplicate identifier errors in declarations | Two copies of the same types, such as a bundled set plus an unneeded `@types` package. | Remove the extra `@types` package. |
| Your `declare module` file is ignored | The file sits outside `include`, or it contains a top-level `import` or `export`. | Move it under an included folder and remove top-level imports and exports. |
When a type seems wrong after installing something, run npx tsc --traceResolution. It prints every location the compiler tried and which file it finally used, which settles the question of where a type came from.
Summary
Declaration files let the compiler check code it cannot see the source of. Libraries either ship them or get them from @types/... packages. You fill any gap with your own declare module files, and you produce them for your own libraries with declaration. Use types to control which @types globals are loaded, and --traceResolution when you cannot tell where a type came from.
Exercise
You add import slugify from "slugify-legacy"; to a strict project and get "TS7016: Could not find a declaration file for module 'slugify-legacy'". Name two ways to fix it, and say which one gives better type safety.
Show answer
First, check whether the DefinitelyTyped package @types/slugify-legacy exists and install it with npm install --save-dev @types/slugify-legacy. Second, write your own declaration in a .d.ts file under an included folder, with no top-level import or export, for example declare module "slugify-legacy" { export default function slugify(input: string): string; }. Real declarations, whether from @types or written by you, give better type safety than the shorthand declare module "slugify-legacy";. The shorthand also removes the error, but it types everything from the package as any.