TypeScript · Lesson 35 of 42
Declaration files and @types packages
Understand .d.ts declaration files, install @types packages for JavaScript libraries, and write a small declaration for untyped code.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will know how TypeScript learns about JavaScript code it did not compile, which is nearly every library you will ever use. You will install type information for popular packages, and write a small declaration yourself when a package has none.
The problem
The JavaScript ecosystem is huge, and most of it was written without types. When you import such a package, TypeScript has no idea what its functions accept or return. The solution is a declaration file, a file ending in .d.ts that contains only types, never code. It describes JavaScript that exists somewhere else.
Packages that bring their own types
Many modern packages include declaration files, and tell the compiler where they are in their package.json. For those, you install the package and everything is typed, with nothing more to do. Your editor shows parameter hints and the compiler checks your calls straight away.
@types packages
Older or smaller packages have no built-in types. A large community project called DefinitelyTyped maintains declarations for thousands of them, published to npm under the @types scope. You install them as development dependencies, since types are only needed while building:
npm install lodash
npm install --save-dev @types/lodashOnce @types/lodash is installed, import _ from "lodash" is fully typed, because the compiler looks for an @types package when it resolves an import. Global names are different. @types/node describes Node.js itself (process, Buffer and the built-in modules such as node:test), and the compiler only loads it if the types option allows it. In older compiler versions every installed @types package was loaded automatically. In current versions (TypeScript 6.0 and later) the default for types is an empty list, so you install the package and also list it:
npm install --save-dev @types/node{
"compilerOptions": {
"types": ["node"]
}
}Without that line, code that uses process or imports node:test fails to compile with an error such as TS2591: Cannot find name 'node:test'. Do you need to install type definitions for node?. Browser globals such as document come from the DOM value of the lib option instead.
If a package has no types and no @types package, strict mode tells you. The message includes the path of the package's JavaScript file, which is shortened here:
error TS7016: Could not find a declaration file for module 'old-library'. '.../node_modules/old-library/index.js' implicitly has an 'any' type.You then have three options, from best to worst: look for types (a newer version of the package or an @types package), write your own declaration, or accept any for that import.
Writing a declaration
Suppose you use a small untyped module called slugify that exports one function. Create a file such as src/slugify.d.ts and describe it with declare module:
// src/slugify.d.ts
declare module "slugify" {
export default function slugify(text: string, separator?: string): string;
}Now import slugify from "slugify" is typed: the compiler knows the function takes a string and an optional string and returns a string. The declaration file produces no JavaScript. It only informs the checker. Make sure the file is included by tsconfig.json (it is, if it lives under a folder listed in include).
For a quick start, you can declare a module with no details at all, which gives its imports the type any:
// src/untyped.d.ts
declare module "old-library";That silences the error but gives no safety, so treat it as a temporary step.
The declare keyword
The declare keyword says "this exists at run time, and here is its type". It creates nothing. A common use is a global value injected by something outside your code, such as a build tool or a script tag:
declare const BUILD_VERSION: string;
function banner(): string {
return `Version ${BUILD_VERSION}`;
}
console.log(banner());This compiles, but if nothing defines BUILD_VERSION at run time, the program fails when it runs. declare is a promise, so only declare things that really exist. You can describe a function the same way (declare function track(event: string): void;).
Extending the global scope
A file that is a module can add to the global scope with declare global. For example, to add a property to window in a browser project:
// src/globals.d.ts
export {};
declare global {
interface Window {
appConfig: { apiUrl: string };
}
}After this, window.appConfig.apiUrl is typed everywhere. This uses the interface declaration merging you met earlier: your Window declaration merges with the one from the browser's types.
Types for your own JavaScript
If you are moving a JavaScript project to TypeScript, two options in tsconfig.json help. allowJs lets the compiler include .js files, and checkJs makes it type-check them, using JSDoc comments as annotations. The migration lesson covers this path in detail. When you publish your own TypeScript library, the compiler can generate .d.ts files for you with declaration: true, so the people who use your package get types.
Where do the built-in types come from?
The lib option controls the declarations the compiler includes for JavaScript and browsers. ES2022 provides Array, Promise and Map. Adding DOM provides document and HTMLElement, which the DOM lesson uses. These are .d.ts files that ship with TypeScript itself, so everything in the language is described the same way as a third-party library.
Common mistakes
Installing @types as a normal dependency. Types are build-time information. Use --save-dev.
Declaring things that do not exist. declare is a promise. If it is wrong, the program crashes at run time.
Leaving declare module "x" empty permanently. It gives imports the type any. Replace it with real types when you can.
Forgetting that .d.ts files must be included. If the compiler does not read your declaration file, the errors persist. Check include in tsconfig.json.
Mismatched @types versions. Match the major version of @types/x to the library you use.
Exercise
Create a tiny JavaScript module greet.js with module.exports = function greet(name) { return "Hello " + name; }, and import it from a TypeScript file with allowJs off. Read the error, then write a greet.d.ts or a declare module block to describe it. Finally, install @types/node, add "node" to the types option if your compiler needs it, and use process.argv in a file with full type checking.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.