Sub topic 3
Ambient Declarations and Published Type Information
Assume you know basic TypeScript types, import and export, tsc, and package.json. This chapter focuses on how TypeScript gets type information when JavaScript or package code does not provide it directly.
Ambient declarations for untyped packages and assets
An ambient declaration describes code without implementing it. A .d.ts file contains declarations that TypeScript uses during checking, but it produces no JavaScript.
For an untyped package, declare its module name and public API:
// src/types/legacy-lib.d.ts
declare module "legacy-lib" {
export function greet(name: string): string;
}
// src/types/assets.d.ts
declare module "*.svg" {
const url: string;
export default url;
}
// src/app.ts
import { greet } from "legacy-lib";
import logoUrl from "./logo.svg";
console.log(greet("Ada"), logoUrl);The wildcard declaration tells TypeScript that the bundler supplies a string for SVG imports. It does not make Node.js or the bundler load the asset.
> callout note > Keep ambient declarations accurate. TypeScript trusts them because it cannot verify an implementation that is not present.
Bundled types and `@types` packages
Prefer types shipped by a package. TypeScript reads a package’s types or typings field. If no bundled types exist, install the matching community package, such as @types/express.
Do not create a local declaration for a package that already provides types. A local declaration can hide the package’s complete API or become inaccurate after an upgrade.
Extending existing modules
Module augmentation reopens an existing module and adds declarations to it:
// user.ts
export interface User {
id: number;
}
// user-extras.ts
import "./user.js";
declare module "./user.js" {
interface User {
nickname?: string;
}
}The import keeps user-extras.ts as a module. Without it, the declaration may be treated as a replacement rather than an augmentation.
Generating and publishing declarations
Set declaration to generate .d.ts files beside compiled output:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src"]
}An exported function becomes a declaration containing its signature, without its implementation.
For publishing, map the package entry point to both runtime JavaScript and types:
{
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}Put the types condition before the runtime condition so TypeScript can select the declaration file.
Exercise
When should you write an ambient declaration instead of installing an @types package?
Show answer
Write one when the package or asset has no suitable published types. Prefer the package's bundled types or a matching @types package when available.