JavaScript and TypeScript course · Module 10: TypeScript in Practice
Declaration Files (.d.ts) and DefinitelyTyped
In this lesson6
Imagine that ancient tablets describing dinosaur species were discovered in Jurassic Park, written in an unknown language. The scientists had to create dictionaries to understand what the tablets describe. In the TypeScript world, declaration files (.d.ts) play the role of these dictionaries: they describe the shape of JavaScript code that has no type information of its own. Without them, a JavaScript library is just any to the compiler (and in strict mode the import fails with an error), so you discover a typo in a method name only in the running application.
What Are .d.ts Files?
Declaration files are files with the .d.ts extension that contain only type information, with no implementation. They describe the shape of JavaScript libraries, external modules and global objects, and the compiler does not generate any code from them. Here is a description of a dinosaur tracking library, in which declare module 'name' states what the module imported under that name looks like:
// file: dinosaur-tracker.d.ts
// Describing an external JavaScript library
declare module 'dinosaur-tracker' {
export interface DinosaurPosition {
id: string;
species: string;
latitude: number;
longitude: number;
lastSeen: Date;
}
export function trackDinosaur(id: string): DinosaurPosition;
export function getAllPositions(): DinosaurPosition[];
export function setAlert(species: string, radius: number): void;
}Thanks to this file, TypeScript knows which functions and types the dinosaur-tracker module exports, even though the module itself is written in plain JavaScript. The implementation did not change by a single byte, only a description was added. When you write a library in TypeScript yourself, the compiler generates such files with the declaration: true option.
The declare Keyword
The declare keyword tells TypeScript: this element exists at runtime, but you do not need to compile it, just trust me. A declaration produces no code, so if you lie, the compiler will not notice. We use it to describe variables, functions, classes and namespaces.
Global Variables
A script loaded with a <script> tag can set a global park configuration. We describe its shape, not its value:
// Global variable available in the browser
declare const PARK_CONFIG: {
name: string;
maxCapacity: number;
securityLevel: 'low' | 'medium' | 'high' | 'critical';
};
// Now we can use it with full type safety
console.log(PARK_CONFIG.name);
console.log(PARK_CONFIG.securityLevel);
// PARK_CONFIG.unknownField; // Compilation error!From now on, referring to a field that does not exist is a compilation error, even though the object itself is created by a completely different script.
Global Functions
You describe functions from an external script the same way, giving only the signature without a body:
// Function defined in an external script
declare function initializeFence(
zone: string,
voltage: number
): { active: boolean; zone: string };
declare function emergencyShutdown(): void;
// Usage with type safety
const fence = initializeFence('raptor-paddock', 10000);
console.log(fence.active); // OK
// console.log(fence.power); // Error! No such propertyThe declaration states what the function takes and returns, while its code lives somewhere else.
Classes and Namespaces
You can also declare whole classes and namespaces, which group related types and functions, as in old libraries loaded globally:
declare class SecuritySystem {
constructor(zones: string[]);
arm(zone: string): void;
disarm(zone: string): void;
getStatus(): Record<string, boolean>;
}
declare namespace ParkAPI {
interface Visitor {
id: string;
name: string;
ticket: 'standard' | 'vip' | 'researcher';
}
function registerVisitor(name: string, ticket: Visitor['ticket']): Visitor;
function getVisitorCount(): number;
}
// Usage
const system = new SecuritySystem(['zone-a', 'zone-b']);
system.arm('zone-a');
const visitor = ParkAPI.registerVisitor('Alan Grant', 'researcher');
console.log(visitor.ticket);Inside declare namespace you do not have to write export, because in an ambient context all members are accessible from the outside.
Writing Your Own Declaration Files
When a JavaScript library has no types, you write your own .d.ts file. This one describes an old dinosaur database. Omit<DinosaurRecord, 'id'> is a record without the id field, which the database assigns, and Partial<DinosaurRecord> makes all fields optional:
// file: types/legacy-dino-db.d.ts
// Describing an old JS library for managing a dinosaur database
declare module 'legacy-dino-db' {
export interface DinosaurRecord {
id: string;
species: string;
diet: 'herbivore' | 'carnivore' | 'omnivore';
weight: number;
height: number;
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
export interface QueryOptions {
limit?: number;
offset?: number;
sortBy?: keyof DinosaurRecord;
order?: 'asc' | 'desc';
}
export class DinoDB {
constructor(connectionString: string);
connect(): Promise<void>;
disconnect(): Promise<void>;
findAll(options?: QueryOptions): Promise<DinosaurRecord[]>;
findById(id: string): Promise<DinosaurRecord | null>;
insert(record: Omit<DinosaurRecord, 'id'>): Promise<DinosaurRecord>;
update(id: string, data: Partial<DinosaurRecord>): Promise<DinosaurRecord>;
delete(id: string): Promise<boolean>;
}
// Default export
export default DinoDB;
}You combine utility types like building blocks: you start with a base type, select fields with Pick or Omit, modify them with Partial or Required, and finally protect them with Readonly. The update data would therefore be described by the type type UpdateDino = Partial<DinosaurRecord>.
DefinitelyTyped and @types Packages
DefinitelyTyped is a huge GitHub repository with declaration files for thousands of JavaScript libraries, maintained by the community. Each set is published to npm as @types/library-name, so instead of writing your own .d.ts files, you install ready-made types:
// Installing types for popular libraries:
// npm install --save-dev @types/express
// npm install --save-dev @types/lodash
// npm install --save-dev @types/node
// After installing @types/express you can write:
import express, { Request, Response, NextFunction } from 'express';
const app = express();
// TypeScript knows the types Request, Response, NextFunction
app.get('/dinosaurs/:id', (req: Request, res: Response) => {
const dinoId: string = req.params.id;
res.json({ id: dinoId, species: 'T-Rex' });
});
// Without @types/express - no type information!
// req, res would be of type "any"You install @types packages as development dependencies (--save-dev), because types are needed only during compilation.
How Does TypeScript Find Declaration Files?
When you import a module, TypeScript looks for types in several places, roughly in this order:
// 1. Types built into the package ("types" field in package.json)
// Many modern libraries have built-in .d.ts
// e.g. axios, zod, prisma
// 2. @types packages from node_modules/@types/
// Automatically recognized by TypeScript
// e.g. @types/react, @types/node
// 3. Custom .d.ts files in the project
// Configuration in tsconfig.json:
// {
// "compilerOptions": {
// "typeRoots": ["./node_modules/@types", "./types"],
// "types": ["node", "express"]
// },
// "include": ["src/**/*", "types/**/*"]
// }
// 4. Triple-slash directives (rarely used)
/// <reference types="node" />
/// <reference path="./custom-types.d.ts" />Before installing @types, check whether the library ships its own types. More and more packages, for example axios or zod, include them, and then a separate package is unnecessary.
Ambient Module Declarations
Sometimes you need to declare a module that is not an npm package, for example a CSS file, an image or JSON. The asterisk in the '*.css' pattern matches every path with that extension:
// file: types/assets.d.ts
// Importing CSS files
declare module '*.css' {
const classes: Record<string, string>;
export default classes;
}
// Importing image files
declare module '*.png' {
const src: string;
export default src;
}
declare module '*.svg' {
const content: string;
export default content;
}
// Importing JSON files
declare module '*.json' {
const value: Record<string, unknown>;
export default value;
}
// Now you can import these files with type safety:
// import styles from './styles.css';
// import logo from './logo.png';
// import dinoData from './dinosaurs.json';The declaration only states what the import returns, while the bundler takes care of actually loading the file. For JSON you can instead enable the resolveJsonModule option, which gives you the exact type of the content.
Extending Existing Types (Declaration Merging in .d.ts)
.d.ts files also let you extend types from external libraries. We add the fields that our middleware sets to the Express request:
// file: types/express-extension.d.ts
// Extending Express types with additional fields
import 'express';
// The req type in handlers comes from the express-serve-static-core package
declare module 'express-serve-static-core' {
interface Request {
userId?: string;
parkZone?: string;
securityClearance?: 'visitor' | 'staff' | 'admin';
}
}
// Now in the application code:
// app.use((req, res, next) => {
// req.userId = 'USR-001'; // OK - TypeScript knows this field
// req.parkZone = 'zone-a'; // OK
// req.securityClearance = 'staff'; // OK
// next();
// });The Request interface merges with the original (declaration merging) instead of replacing it. We extend the express-serve-static-core module, because that is where the type of req in handlers comes from, and import 'express' turns the file into a module, which is required for a module augmentation.
Declaration files (.d.ts) and the DefinitelyTyped ecosystem are the foundations of working with TypeScript in the real world: thanks to them you use thousands of JavaScript libraries with full type safety. My order: first the types built into the package, then @types, and your own .d.ts file last, starting with the functions you actually use. In the editor below you will practice declarations, and in the next lesson you will learn template literal types.
Remember: a .d.ts file is a dictionary for an ancient tablet, one that does not change a single character on it but lets you read it safely.
Code for this lesson: index.ts
// Declaration files (.d.ts) and DefinitelyTyped
// Jurassic Park - Type Declaration System
// 1. Simulation: declaring an external JS library
// In a real project this would be in a .d.ts file
// declare module 'dinosaur-tracker' {
// export function trackDinosaur(id: string): DinosaurPosition;
// }
// 2. Declaring global variables
// declare const PARK_CONFIG: { name: string; securityLevel: string };
// 3. Simulation of using types from DefinitelyTyped
// Imagine we installed @types/express
interface DinosaurRecord {
id: string;
species: string;
diet: 'herbivore' | 'carnivore' | 'omnivore';
weight: number;
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
interface QueryOptions {
limit?: number;
offset?: number;
sortBy?: keyof DinosaurRecord;
order?: 'asc' | 'desc';
}
// Simulation of a class from an external library
class DinoDB {
private records: DinosaurRecord[] = [
{ id: 'D001', species: 'T-Rex', diet: 'carnivore', weight: 7000, dangerLevel: 5 },
{ id: 'D002', species: 'Triceratops', diet: 'herbivore', weight: 6000, dangerLevel: 2 },
{ id: 'D003', species: 'Velociraptor', diet: 'carnivore', weight: 80, dangerLevel: 4 },
{ id: 'D004', species: 'Brachiosaurus', diet: 'herbivore', weight: 56000, dangerLevel: 1 },
];
findAll(options?: QueryOptions): DinosaurRecord[] {
let result = [...this.records];
if (options?.sortBy) {
result.sort((a, b) => {
const val = String(a[options.sortBy!]).localeCompare(String(b[options.sortBy!]));
return options.order === 'desc' ? -val : val;
});
}
const offset = options?.offset || 0;
const limit = options?.limit || result.length;
return result.slice(offset, offset + limit);
}
findById(id: string): DinosaurRecord | null {
return this.records.find(r => r.id === id) || null;
}
}
// 4. Extending types (Declaration Merging)
// In a real project we extend e.g. Express.Request
interface ParkRequest {
userId?: string;
parkZone?: string;
securityClearance?: 'visitor' | 'staff' | 'admin';
}
// Test
const db = new DinoDB();
console.log("=== Dinosaur database (simulation @types) ===");
console.log("\nAll records:");
db.findAll().forEach(d =>
console.log(` ${d.species} (diet: ${d.diet}, danger: ${d.dangerLevel})`)
);
console.log("\nSorted by weight (desc), limit 2:");
db.findAll({ sortBy: 'weight', order: 'desc', limit: 2 }).forEach(d =>
console.log(` ${d.species}: ${d.weight}kg`)
);
console.log("\nLooking for T-Rex:");
const trex = db.findById('D001');
if (trex) {
console.log(` Found: ${trex.species}, danger level: ${trex.dangerLevel}`);
}
// 5. Ambient declarations - types for assets
// declare module '*.css' { const classes: Record<string, string>; export default classes; }
// declare module '*.png' { const src: string; export default src; }
console.log("\n=== Declaration types (.d.ts) ===");
console.log("• declare module - declaration of an external module");
console.log("• declare const/function - global variables/functions");
console.log("• @types/xxx - ready-made types from DefinitelyTyped");
console.log("• *.d.ts - files with types only, without implementation");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What do .d.ts files contain in TypeScript?
2. What are the DefinitelyTyped repository and @types packages?
Hands-on tasks in the game
- Code editor
Write type declarations for an external library and global variables using declare.
- Click in order
Arrange the elements of an external module declaration in TypeScript:
- Code editor
Create type declarations for the dinosaur-tracker module using declare module.
- Horizontal ordering
Arrange the elements of a Partial type declaration in the correct order:
- Vertical ordering
Arrange the steps for building a complex utility type: