What Is a .d.ts File?
A .d.ts file is a TypeScript file that contains types and nothing else. No function bodies, no
loops, no runtime values — just declarations describing code that lives somewhere else. The d
stands for declaration, and that is the whole job: a .d.ts file tells the compiler what a
piece of JavaScript looks like, without being that JavaScript.
You have already used dozens of them without noticing. Every @types/* package you install is a
bundle of declaration files. The lib.dom.d.ts that gives you document.querySelector is one.
When an import turns red with "could not find a declaration file", a missing .d.ts is what the
compiler is complaining about.
What a .d.ts file is
Here is a complete declaration file. It describes a module that loads user profiles:
export interface UserProfileDts {
id: string
displayName: string
avatarUrl?: string
}
export declare function loadProfileDts(id: string): Promise<UserProfileDts>
export declare const DEFAULT_AVATAR_DTS: stringEvery member is a signature. loadProfileDts has a return type but no body, and DEFAULT_AVATAR_DTS
has a type but no value. That is what declare means: this exists at runtime, take my word for it.
The actual implementation lives in a plain JavaScript file next to it:
export async function loadProfileDts(id) {
const res = await fetch(`/api/users/${id}`)
return res.json()
}
export const DEFAULT_AVATAR_DTS = '/img/avatar.png'Two files, one module. TypeScript reads the declarations when it type-checks, the runtime loads the
JavaScript, and neither knows about the other. A .d.ts file is erased completely at compile time —
it emits no output, because there is nothing to emit.
Where .d.ts files come from
Declaration files reach your project through four routes, and it helps to know which one you are on.
Bundled with the package. Modern libraries ship their own. You install zod or date-fns,
TypeScript finds dist/index.d.ts through the types field in the package's package.json, and
everything works. No extra step.
From DefinitelyTyped. Older libraries ship plain JavaScript, and the community maintains types
separately under the @types scope:
[object Object]That drops a tree of .d.ts files into node_modules/@types/lodash, and TypeScript picks up
anything under node_modules/@types automatically. The npm and TypeScript guide
covers which packages need this and which do not.
Emitted by the compiler. If you publish a library written in TypeScript, tsc generates the
declaration files for you. More on that below.
Written by hand. When a dependency has no types and nobody has written @types for it, you
write the declaration yourself. This is the case worth learning properly.
Writing a .d.ts file for an untyped package
Import an untyped package and the compiler stops with
TS7016: could not find a declaration file for module. The fix is an ambient
module declaration — a .d.ts file in your own source tree that describes somebody else's package.
Create src/types/legacy-slugify.d.ts:
declare module 'legacy-slugify-dts' {
export default function slugifyDts(input: string): string
}That is it. The import now resolves, and slugifyDts is typed as taking a string and returning one.
You are not patching the library — you are promising the compiler what it contains.
Nothing stops you from describing more of the surface. Classes, options objects, named exports all work the same way:
declare module 'chart-widget-dts' {
export interface ChartOptionsDts {
width: number
height: number
legend?: boolean
}
export class ChartDts {
constructor(el: HTMLElement, options: ChartOptionsDts)
render(): void
destroy(): void
}
}The class has no bodies because it does not need them. Ambient declarations describe shape, and the real class arrives at runtime from the package.
When you genuinely do not care — a build-only script, a one-off import — there is a shorthand:
[object Object]Every export from that module is now any. It silences the error, and it gives you nothing else.
Treat it as a deliberate placeholder rather than a finish line.
One catch worth knowing: declaration files only help if TypeScript actually looks at them. If your
include patterns miss src/types, the file never enters the program, the ambient declaration
never takes effect, and the import keeps failing with the same
TS7016 you were trying to silence. A types array or a typeRoots entry that
names an @types package the compiler cannot find is a different failure —
TS2688: cannot find type definition file. The
tsconfig.json reference covers which options control that search.
Declaring globals
Not everything arrives through an import. Feature flags injected by a server-rendered script tag,
values attached to window by a third-party snippet, globals added by a bundler plugin — none of
those have a module to declare.
For those, a declaration file can reach into the global scope:
export {}
declare global {
interface Window {
__APP_FLAGS_DTS__: Record<string, boolean>
}
}The export {} at the top is not decoration. It turns the file into a module, and declare global
is only allowed inside one. Leave it out and the compiler rejects the augmentation.
With that in place, the global is typed everywhere:
const flagsDts = window.__APP_FLAGS_DTS__
const betaCheckoutDts = flagsDts.newCheckout ?? falseBecause interface Window merges with the one from the DOM library, you are extending the existing
type rather than replacing it. Everything window already had is still there.
Emitting .d.ts files for a library you publish
If your package is written in TypeScript, you do not hand-write declarations — you turn on one compiler flag:
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"outDir": "dist"
}
}Now every compiled file gets a .js and a matching .d.ts in dist. declarationMap adds
.d.ts.map files so that "go to definition" in a consumer's editor jumps to your original source
instead of the generated signatures — a small flag that makes your package much nicer to use.
Then point package.json at the result:
{
"name": "shipping-kit",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": ["dist"]
}The types field is what consumers' compilers read. Ship dist without it and your package looks
untyped to everyone downstream. Packages with ESM and CommonJS builds need
declarations for each entry point, usually through the exports map rather than a single types
field.
Source like this emits cleanly:
export interface ShippingZoneDts {
code: string
baseCents: number
perKgCents: number
}
export function shippingCostDts(zone: ShippingZoneDts, weightKg: number): number {
return zone.baseCents + Math.ceil(weightKg) * zone.perKgCents
}There is one failure mode worth knowing. The emitted declaration can only mention names that it is
able to write down. A type declared at module scope is fine either way — tsc copies the interface
into the .d.ts next to the function even when you never exported it — but a type that exists only
inside a function body has no such name, and the compiler stops with TS4060: return type of
exported function has or is using private name. Declaring the type at module scope and exporting it
avoids that, and consumers who want to annotate a variable with the return type need the export
anyway:
export interface RateDts {
multiplier: number
}
const rateTableDts: Record<string, RateDts> = {
standard: { multiplier: 1 },
express: { multiplier: 1.8 },
}
export function lookupRateDts(code: string): RateDts {
return rateTableDts[code] ?? { multiplier: 1 }
}Drop the export in front of RateDts and the build still passes — the interface simply lands in
the .d.ts without one. But consumers are then handed a function whose return type they have no way
to name, which is rarely what you want from a package you publish.
Typing your own JavaScript files
The same trick works inside your own codebase. A half-migrated project often has JavaScript modules that the TypeScript side keeps importing, and you do not want to convert them yet.
Put a declaration file next to the source with a matching name — utils/parse-csv.js gets
utils/parse-csv.d.ts — and TypeScript pairs them up automatically:
export declare function parseCsvDts(
text: string,
delimiter?: string,
): string[][]The import now type-checks against those signatures while the runtime keeps loading the original
JavaScript. Convert the file properly later and you delete the declaration; until then the rest of
the codebase gets real types instead of any.
The pairing resolves on its own: TypeScript looks for utils/parse-csv.d.ts before it considers
utils/parse-csv.js, so the declaration types the import whether or not allowJs is on — the same
mechanism that lets @types/* packages work in projects that never touch JavaScript. What allowJs
changes is whether the .js source enters the program at all, and with it whether TypeScript could
have inferred types from JSDoc comments instead. Either way the hand-written declaration wins over
inference. That is a real trade-off:
inference from JSDoc comments stays in sync with the code on its own, while a hand-written .d.ts
quietly drifts the moment someone edits the implementation and forgets the declaration. For a file
you plan to convert soon, the declaration is fine. For one that will sit there for a year, JSDoc
types in the JavaScript itself age better.
Pulling in declarations explicitly
Most of the time resolution is automatic. When it is not, a triple-slash directive loads a declaration file by hand:
[object Object]It belongs at the very top of a file, above everything else, and it is mostly a legacy tool now —
the types array in tsconfig.json does the same job for a whole project and is easier to audit.
Reach for the directive when a single declaration file depends on another, which is exactly the
situation inside published .d.ts bundles.
.d.ts vs .ts: when not to write one
The common mistake is reaching for a declaration file when an ordinary .ts file would do.
Write a .d.ts file when you are describing code you do not compile — an untyped dependency, a
global injected at runtime, a JavaScript file you are not ready to convert. Write a normal .ts
file for anything you own and compile. Types declared in a regular module are exported and imported
like any other value, and you keep the implementation and its types in one place.
The other rule: never edit a generated .d.ts in dist. It is build output. The next tsc run
overwrites it, and the change belongs in the source file anyway.
And if you are sorting out TypeScript's other extensions while you are here, the .tsx file guide covers the one that holds JSX.
Summary
A .d.ts file carries types without runtime code. Most of them arrive automatically, bundled with
packages or installed from @types. You write one by hand when a dependency has none — declare module 'pkg' with whatever surface you actually use — or when something is injected globally, in
which case export {} plus declare global is the pattern. When you publish, set
declaration: true and point types at the emitted file, and remember that every type in a public
signature has to be exported too.
Become a TypeScript Pro
Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges