Capítulo 15 de 36
Everything TypeScript knows about code it didn't write itself — built-in JS APIs, DOM globals, third-party libraries — comes from .d.ts declaration files: type-only files with no executable code and no JS output, purely for type-checking.
.ts vs .d.ts: .ts files are implementation files (types + real code, compile to .js). .d.ts files declare only types/signatures, produce no JS output, and exist purely so the type-checker knows a value/API exists and what shape it has.lib.[something].d.ts files bundled with TypeScript — covering standard JS built-ins (Math, Object, string/array methods) and, by default, browser DOM APIs (window, document).target gates which built-in APIs are considered available — e.g. String.prototype.startsWith (ES6+) is flagged as an error under target: "ES5", because TS varies which lib files it includes by default based on target. The lib compiler option gives finer-grained manual control over exactly which declaration files are considered in scope, independent of target..d.ts files as part of the published package; nothing extra to install.@types — a centralized community repo of declaration files for thousands of untyped libraries, auto-published to npm under the @types/* scope (package name always mirrors the underlying library's name, e.g. @types/react for react). TypeScript auto-discovers anything under node_modules/@types with no extra config.declare module "some-untyped-module"; in a project .d.ts file gives that import path an implicit any type without writing a real declaration file — a stopgap, not a substitute for real types.// project.d.ts
declare module "some-untyped-module";
any.| Source of types | When to use |
|---|---|
| Bundled with the package | check first — many modern packages ship their own .d.ts |
@types/<package> (DefinitelyTyped) | package itself has no bundled types |
| Hand-written declaration file | neither of the above exists |
declare module "x"; | quick stopgap — types the whole module as any |
.d.ts files never produce JavaScript output — they're a type-checking-only artifact, distinct from .ts implementation files.target/lib control which built-in JS/DOM APIs TypeScript considers available — a startsWith error under an older target is a feature, not a bug, catching genuine runtime incompatibility ahead of time.@types/*, before reaching for a hand-written or stopgap declare module — in that order of preference.import/export model that declaration files describe types for.