Declaration Files & DefinitelyTyped
TypeScript types for a library can come from three sources: bundled with the library (signaled by the types field in package.json), from the DefinitelyTyped community repository via @types/<package> packages, or from a hand-written .d.ts file in the project. TypeScript resolves these in priority order: bundled types win over @types, which win over project-local declarations. Understanding this chain prevents the common failure of writing a .d.ts file for a library that already has community types — a hand-written declaration that silently shadows an upstream one, creating a maintenance burden that should never have existed.
DefinitelyTyped is a GitHub repository that hosts community-maintained type definitions for thousands of JavaScript libraries that do not ship their own types. The packages it produces are published under the @types scope on npm. When a TypeScript project installs @types/lodash, it receives a .d.ts file set maintained by contributors who track lodash's API — not by the lodash authors themselves. This separation between implementation and type definitions was the dominant model before TypeScript adoption became widespread; today, most actively maintained libraries bundle their own types, but DefinitelyTyped remains essential for libraries with slower adoption cycles.
The lifecycle of type support for a library follows a predictable arc: the library ships with no types → a contributor adds types to DefinitelyTyped → the library eventually bundles its own types → the @types package becomes redundant and is deprecated. Projects that understand this arc make better decisions about where to invest type authoring effort and when to remove stale @types dependencies. Acting on this understanding means periodically auditing package.json devDependencies for @types packages whose corresponding library now bundles types, and removing the now-redundant @types package to avoid the maintenance cost of tracking its updates.
Understanding the three-source model also clarifies the cost structure of choosing each source. Bundled types cost nothing to install and are maintained by the library authors; they are the lowest-cost, highest-confidence option. DefinitelyTyped packages cost a pnpm add -D and carry a risk of falling behind the library version; they are the standard option for widely used libraries that do not bundle types. Project-local declarations carry an ongoing maintenance cost proportional to how completely they describe the library; they are the last resort.
Design Thinking
.d.ts files: declarations without implementation
A declaration file is TypeScript syntax with no runtime value — it describes the shape of a JavaScript module without emitting any code. A .d.ts file may declare functions, classes, interfaces, types, modules, and globals, but none of these declarations produce JavaScript output. The file is the bridge between the JavaScript world, where types are absent at runtime, and the TypeScript world, where types are required at compile time.
Declaration files follow the same syntax as regular TypeScript files with one constraint: they may not contain implementation. A declare function fetch(url: string): Promise<Response> tells TypeScript the shape of fetch without providing a function body. A declare module 'some-library' tells TypeScript the module exists and what it exports, without replicating the library's source. This constraint is what makes declaration files usable as overlays — they can be applied on top of any JavaScript library without modifying that library.
The distinction between a full declaration and an ambient module declaration matters for the quality of type safety delivered. A full declaration — one that enumerates every exported function, class, and type with accurate signatures — provides complete type safety. An ambient module declaration, declare module 'lib-name' with an empty body, tells TypeScript only that the module exists; all exports are implicitly typed as any. Both suppress the "cannot find module" compiler error, but only the first provides actionable type information that allows the compiler to catch misuse at call sites.
Declaration files are also the mechanism for describing global augmentations: adding properties to window, extending built-in prototypes, or declaring ambient variables that come from build-tool injection (such as __DEV__ flags injected by webpack). These global declarations live in .d.ts files that are picked up by typeRoots configuration or included explicitly in tsconfig.json. The same rules apply: the more precisely scoped the declaration, the less risk of accidentally widening TypeScript's view of the global environment in ways that mask real errors.
A practical workflow for deciding which source to use for a given library's types starts at the library itself: check whether the package exports a types field in its package.json, or whether the entry point has a co-located .d.ts file. If bundled types exist, nothing further is required. If they do not, run npm info @types/<package-name> to determine whether a DefinitelyTyped package exists and whether its version aligns with the library version in use. Only if neither source is available should a project-local declaration be written, and only after confirming that the DefinitelyTyped package truly does not exist rather than simply not appearing in search results — the @types scope on npm is large, and some community type packages use unconventional naming. This three-step check, performed in under two minutes, prevents the most common source of unnecessary project-local declarations: engineers who write declarations because they were unaware that community types existed.
Version alignment between a library and its DefinitelyTyped package is a recurring maintenance concern. DefinitelyTyped packages follow a major.minor versioning scheme where the first two version segments correspond to the library version. @types/lodash@4.14 types lodash version 4.14. When a library releases a new major version that introduces breaking API changes, the DefinitelyTyped package must be updated separately — the library update and the types update are independent npm packages managed by different teams. Using @types/some-library@3.x types while the installed library is some-library@4.x produces a mismatch where the types describe an API surface that no longer exists, and the compiler provides misleading safety guarantees. Dependency management tooling such as npm outdated and tsd can surface these mismatches; including type package version alignment as a criterion in dependency update PRs prevents silent divergence from accumulating across library upgrades. Renovate and Dependabot both support grouping library upgrades with their corresponding @types package updates into a single PR, which is the lowest-friction approach for keeping versions synchronized without requiring manual tracking. This pairing strategy also ensures that the type alignment check is part of every dependency update review, making version drift a visible concern in the normal pull request workflow rather than something discovered only when a runtime mismatch causes a production incident.
Module augmentation: extending third-party types
When a library's types are incomplete or incorrect, module augmentation allows a project to extend them without forking the package or maintaining a full parallel declaration. A declare module 'library-name' block inside a .d.ts file merges with the existing module declaration rather than replacing it. This means interface Options { newField: string } inside the augmentation block adds newField to the library's Options interface globally across the project. TypeScript merges the augmented interface at compile time, and every call site that uses Options sees the extended shape.
Module augmentation is tracked in version control and cleaned up in a single commit when the upstream type is fixed. The alternative — casting at every call site with as ExtendedOptions — suppresses the error at one location without informing other call sites that the field exists, accumulates across the codebase as the library is used in more places, and requires a search-and-replace to clean up when the upstream type eventually adds the field. The search-and-replace is also error-prone: it must distinguish casts that were temporary workarounds from casts that exist for other reasons.
The same mechanism enables global scope augmentation. Extending interface Window { analytics: AnalyticsAPI } or adding properties to process.env via namespace NodeJS { interface ProcessEnv { API_KEY: string } } follows the same merge semantics. The augmentation file must be a module (it must contain at least one import or export) for the merge to work correctly; a plain script-context .d.ts file would declare a competing global instead of merging into the existing one, producing duplicate identifier errors or unexpected type widening depending on resolution order.
Module augmentation has one important scope rule: the augmentation is only active when the augmentation file is included in the TypeScript compilation. Files are included through include patterns in tsconfig.json, explicit files entries, or being transitively imported by a file that is included. An augmentation file that lives in a src/types/ directory is only effective if that directory is covered by the compilation configuration — a detail worth verifying when augmentations appear to have no effect.
Ambient module declarations and wildcard declarations
When a library has no @types package and no bundled types, a minimal ambient module declaration — declare module 'lib-name' with no body — silences the type error while providing no type safety. The module is typed as any, which is less useful than a full declaration but more useful than a compile error that blocks the build. This is acceptable as a temporary measure that unblocks the project while a proper solution is arranged.
An ambient module declaration is not a permanent solution. It gives no information to the TypeScript compiler about what the module exports, what argument types its functions accept, or what they return. Call sites receive any and lose all type checking. A complete declaration — one that types the actual exports accurately — should be contributed upstream to DefinitelyTyped so that every project using the library benefits, not just the one that wrote the declaration first.
A true wildcard declaration — declare module '*' — is a different and more dangerous tool. It tells TypeScript to accept any unresolvable module import as any, which silences type errors for every missing module in the project, not just the one that needed covering. This pattern is occasionally legitimate in specific bundler plugin contexts (for example, declaring that all .svg imports produce a string URL, or that all .graphql imports produce a DocumentNode), but should never be used as a blanket fix for missing @types packages. When a wildcard declaration is used correctly for asset imports, it is typically written as declare module '*.svg' { const content: string; export default content; } — a pattern that is scoped to a file extension rather than truly open-ended.
Type resolution priority and the risk of shadowing
TypeScript's resolution order — bundled types → @types packages → project-local declarations — creates a shadowing risk that runs in the wrong direction from what engineers typically intend. If a project already has a project-local .d.ts file for a library and later installs the library's @types package, the @types package takes precedence and the project-local file becomes dead code. This is usually the desired outcome, but the dead file persists silently and may confuse future readers who wonder which declaration is in use.
The more problematic direction is when typeRoots or paths configuration causes TypeScript to prefer project-local declarations over the authoritative ones. In this case, the hand-written types silently replace the accurate bundled types, the compiler accepts code that depends on the stale declarations, and the discrepancy surfaces only at runtime. Auditing project-local declarations when adding new @types packages or upgrading libraries with bundled types is part of keeping the type environment coherent. A useful practice is to search for declare module in the codebase whenever a library is upgraded to a version that begins bundling types.
Writing declaration files for internal packages
Internal packages — shared utilities, design system libraries, or platform SDKs maintained by the same organization — sometimes need declaration files when they are distributed as pre-built JavaScript rather than TypeScript source. In this case, a .d.ts file accompanies the compiled output and is referenced via the types field in the internal package's package.json. This is equivalent to how third-party packages bundle their types: the consumer project gains type safety without needing to include the internal package's source in its own compilation.
When internal packages are consumed across monorepo workspaces, TypeScript project references (references in tsconfig.json) are the preferred mechanism over manual .d.ts files. Project references allow TypeScript to traverse the dependency graph, use incremental builds across packages, and serve accurate types from source rather than from a potentially stale compiled output. The decision between emitting declaration files and using project references depends on whether the internal package is consumed as source or as a build artifact.
The typeRoots and types compiler options
The typeRoots option in tsconfig.json controls which directories TypeScript searches for automatic @types inclusion. By default it searches node_modules/@types at every level of the directory tree. Setting typeRoots to a custom list limits automatic inclusion to those directories and can be used to make project-local declaration directories discoverable without listing every file individually.
The types option is an explicit allowlist: when set, TypeScript only automatically includes @types packages listed in the array, even if other @types packages are installed. This is useful in browser projects where @types/node is installed as a transitive dependency but its globals (process, Buffer) should not be visible in browser code. Setting "types": [] in a browser-targeted tsconfig.json opts out of all automatic @types inclusion, requiring every needed type package to be either listed explicitly or imported directly at a call site.
Understanding these two options prevents a common class of confusion where a type definition is installed but not visible, or is visible when it should not be. When a declaration file or @types package appears to have no effect, the first diagnostic step is to verify that the file is in a directory covered by typeRoots or include, and that the package is not excluded by a types allowlist.
A related option is skipLibCheck: true, which tells TypeScript to skip type-checking of all .d.ts files — including those in node_modules. This option is common in project templates because it suppresses errors in third-party type definitions that are not the project's responsibility to fix. It does not skip the type definitions themselves; the types are still used to check the project's source files. Understanding this distinction is important: skipLibCheck eliminates noise from broken third-party declarations without reducing the type safety of the project's own code. The tradeoff is that a declaration file in the project's own src/types/ directory is also skipped, so errors introduced by hand-written declarations may not surface until the types are consumed at a call site.
Best Practices
MUST install @types/<package> for every JavaScript dependency used in TypeScript files before concluding that a library has no type support. Many widely used libraries ship types via DefinitelyTyped rather than bundling them. Running pnpm add -D @types/<package> is the first step; checking the DefinitelyTyped search at https://www.typescriptlang.org/dt/search/ is the second. A library genuinely without types is rare for anything in the npm top 10,000.
MUST NOT write manual type declarations for packages that have official or DefinitelyTyped-published types. Manual declarations go stale when the library updates and create false confidence — the TypeScript compiler accepts the code while the actual library behavior may differ from the declared types. Developers MUST NOT assume a library lacks types without first checking both the package's own package.json for a types field and the @types scope on npm.
MUST NOT use declare module '*' as a blanket suppressor for unresolved module errors. A wildcard module declaration silences type errors for every missing import in the project, not only the one that triggered the error. The correct scope for an ambient module declaration is the specific module name: declare module 'lib-name'. The wildcard form is only appropriate in narrow bundler-plugin contexts where every import of a given file extension should be treated uniformly — and even then, the wildcard should be typed as precisely as the asset format allows.
SHOULD use module augmentation to extend third-party types rather than casting at call sites. Module augmentation is a declaration that TypeScript enforces everywhere the augmented type is used. A cast (as ExtendedOptions) suppresses the error at one call site without informing other call sites that the field exists. Augmentation is also removed cleanly in a single commit when the upstream type is fixed — search and replace on cast sites is not.
SHOULD contribute missing or corrected types to DefinitelyTyped rather than maintaining project-local declarations indefinitely. A .d.ts file maintained in one project benefits only that project and creates an ongoing maintenance obligation as the library evolves. Types contributed to DefinitelyTyped are versioned, tested against the library's published API, and available to the entire ecosystem. The contribution process is documented at https://github.com/DefinitelyTyped/DefinitelyTyped.
SHOULD periodically audit @types devDependencies and remove those whose corresponding library now bundles its own types. An installed @types package for a library that has since added bundled types is dead weight: the bundled types take precedence, the @types package is never consulted, but it still appears in package.json, receives update notifications, and can confuse engineers investigating the project's type setup. Removing it simplifies the dependency graph without affecting type safety.
Visual
The following diagram shows the order in which TypeScript resolves types for an imported module. Resolution stops at the first successful match; reaching the final step produces a compile error. Yellow indicates that the resolution succeeded but the resulting types may be incomplete or imprecise; green indicates authoritative types; red indicates failure.
The yellow path (project-local declaration) is the only one that requires active engineering judgment. Arriving at the yellow path during development is a signal to investigate: is there an @types package that was simply not installed yet? Is this a library that could benefit from a DefinitelyTyped contribution? Is the project-local declaration complete enough to be trusted, or does it expose any at call sites?
The red path (compile error) is information, not just a failure. It means TypeScript found no type information for the module — which is better than silently accepting any. A compile error is the correct behavior in the absence of types; it is a prompt to take one of the green or yellow paths deliberately rather than by accident.
Example
The following example shows module augmentation in a real scenario: extending Express's Request type to carry a user property populated by authentication middleware. This is a common pattern because Express does not know about application-specific middleware in its base types, so req.user is not part of the default Request interface.
The user model that the augmentation references:
// src/models/user.ts
export interface AuthenticatedUser {
id: string;
displayName: string;
email: string;
roles: string[];
}The augmentation file lives in src/types/express.d.ts and must be a module — the export {} at the end makes it a module scope rather than a script scope, which is required for the declare module merge to work correctly:
// src/types/express.d.ts
import type { AuthenticatedUser } from '../models/user';
declare module 'express-serve-static-core' {
interface Request {
user?: AuthenticatedUser;
}
}
export {};The tsconfig.json must include the types directory so TypeScript picks up the augmentation file:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"outDir": "./dist"
},
"include": [
"src/**/*"
]
}The augmented Request interface is then available at every call site without any import or cast. TypeScript knows req.user exists and what its shape is because it merged the augmentation into the Express Request interface at compile time:
// src/middleware/requireAuth.ts
import type { Request, Response, NextFunction } from 'express';
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
if (!req.user) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
// TypeScript knows req.user is AuthenticatedUser here — no cast needed
next();
}// src/middleware/requireRole.ts
import type { Request, Response, NextFunction } from 'express';
export function requireRole(role: string) {
return (req: Request, res: Response, next: NextFunction): void => {
if (!req.user) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
if (!req.user.roles.includes(role)) {
res.status(403).json({ error: 'Forbidden' });
return;
}
next();
};
}// src/routes/profile.ts
import type { Request, Response } from 'express';
export function getProfile(req: Request, res: Response): void {
// req.user is typed as AuthenticatedUser | undefined
const user = req.user;
if (!user) {
res.status(401).end();
return;
}
res.json({
id: user.id,
name: user.displayName,
email: user.email,
});
}
export function updateProfile(req: Request, res: Response): void {
const user = req.user;
if (!user) {
res.status(401).end();
return;
}
// req.body is typed as any by Express, so validation is still needed
// but user.id is correctly typed — no cast required
const { displayName } = req.body as { displayName?: string };
if (!displayName) {
res.status(400).json({ error: 'displayName is required' });
return;
}
res.json({ id: user.id, displayName });
}Without the augmentation, every access to req.user would require a cast ((req as any).user) or a custom AuthenticatedRequest interface re-declared at each route file. With augmentation, the type flows automatically from a single source of truth. When the pattern is eventually replaced — for example, by a framework with built-in authentication context — the augmentation file is deleted in a single commit and the compiler reports every site that still references req.user.
To contrast, here is what a minimal ambient module declaration looks like for an untyped library, used as a temporary measure while a proper declaration is being prepared. The comment makes the provisional status explicit and links to a work item:
// src/types/untyped-analytics.d.ts
// TEMPORARY — replace with full types or @types/some-analytics when available.
// This types all imports from 'some-analytics' as `any`.
// Tracked: https://github.com/org/repo/issues/1234
declare module 'some-analytics';A more informative version, written once enough of the API surface is understood to be worth typing:
// src/types/some-analytics.d.ts
// Full local declaration until @types/some-analytics is published.
// Covers only the subset of the API used by this project.
declare module 'some-analytics' {
export interface TrackOptions {
event: string;
properties?: Record<string, unknown>;
userId?: string;
}
export function track(options: TrackOptions): Promise<void>;
export function identify(userId: string, traits?: Record<string, unknown>): void;
export function page(name: string, properties?: Record<string, unknown>): void;
}This version provides real type safety for the parts of the API the project uses, while making the provisional scope clear through comments. When @types/some-analytics is published, the file is deleted in a single commit.
Common Mistakes
Installing @types/node (or any @types package) globally rather than as a project dependency causes type definitions to leak across projects that share the same global Node environment. When @types/node is installed globally, every TypeScript project on the machine gains access to Node globals (process, Buffer, __dirname) even if the project is a browser-only application. Browser-only projects that accidentally depend on Node globals compile locally but fail in CI or on other machines where the global package is absent.
The correct installation scope is always per-project: pnpm add -D @types/node. This makes the dependency explicit in package.json, reproducible across environments, and scoped to the projects that actually run in Node. For browser projects that incidentally have @types/node as a transitive dependency, the "types": [] option in tsconfig.json prevents the Node globals from being automatically included.
Using declare module '*' when only one specific module needs an ambient declaration accidentally silences type errors for every unresolvable import in the project. A wildcard module declaration is a single statement that matches any module name TypeScript cannot otherwise resolve. If a project has a genuinely missing @types package, a misspelled import path, or a deleted module, the wildcard declaration hides all of those errors simultaneously. The symptom is a codebase that compiles cleanly despite containing real problems.
The correct fix is always a named ambient module declaration — declare module 'specific-lib-name' — which scopes the suppression to exactly one module and leaves all other unresolvable imports as compile errors where they belong. If multiple unrelated modules need ambient declarations, each gets its own named declare module statement; combining them into a wildcard is never the right approach.
Writing a new .d.ts file without checking whether the library already bundles types can cause the hand-written declarations to silently shadow the bundled ones in certain TypeScript resolution configurations. If typeRoots or paths in tsconfig.json causes TypeScript to check project-local declarations before the package's own node_modules entry, the hand-written file takes precedence. The bundled types — which are authoritative and kept up to date by the library authors — become invisible.
The symptom is subtle: code compiles, but the types in use are the stale hand-written ones rather than the current library types. Call sites that use APIs added in recent library versions typecheck against the old hand-written signatures and may silently receive any for the new parameters. Checking package.json for a types or typings field before writing any .d.ts file prevents this entire class of error. The check takes seconds; the consequence of skipping it can require hours of debugging when a library upgrade produces unexpected runtime behavior.
Related FEEs
- FEE-1700 — TypeScript Overview
- FEE-1701 — Type System Fundamentals & Type Inference (structural typing is the basis for understanding what declarations describe)
- FEE-1706 — tsconfig & Strict Mode (typeRoots, types, and skipLibCheck are tsconfig concerns)
- FEE-1708 — Runtime Validation & Schema Libraries (declaration files describe compile-time types; runtime validation fills the gap TypeScript cannot cover)
References
- TypeScript Handbook: Declaration Files — https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html
- DefinitelyTyped GitHub — https://github.com/DefinitelyTyped/DefinitelyTyped
- TypeScript search for @types packages — https://www.typescriptlang.org/dt/search/
- TypeScript Handbook: Module Augmentation — https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
- TypeScript Handbook: Declaration Reference — https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html
- TypeScript tsconfig Reference: typeRoots — https://www.typescriptlang.org/tsconfig/#typeRoots
- TypeScript tsconfig Reference: types — https://www.typescriptlang.org/tsconfig/#types
- TypeScript tsconfig Reference: skipLibCheck — https://www.typescriptlang.org/tsconfig/#skipLibCheck
- DefinitelyTyped contribution guide — https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md
- TypeScript Handbook: tsconfig — https://www.typescriptlang.org/tsconfig/