← Back to TypeScript Course | Chapter 11: Type Declarations and DefinitelyTyped | Lesson 2 of 5

Writing Declaration Files

You can write your own .d.ts files when TypeScript needs type information for JavaScript code or a custom library. A declaration file describes the public API without implementing it.

Declaring a Function

Declaring a function means writing out its parameter names, parameter types, and return type as a signature, with no function body, since a .d.ts file only describes shape, never behavior.

Example: Declaring a Function

typescript
declare function formatDate(date: Date, pattern: string): string;
// No body -- just the signature.
console.log("Function declared: formatDate(date, pattern) -> string");

Declaring Objects

Declaring object shapes usually means writing an interface that lists each expected property and its type, which then gets used as the type annotation for any variable meant to hold that kind of object.

Example: Declaring Objects

typescript
interface UserRecord {
  id: number;
  name: string;
}
declare const currentUser: UserRecord;
console.log("Object shape declared via interface UserRecord");

Declaring a Module API

Declaring a module's public API means writing a declare module block that lists every export the module makes available, so importing from it elsewhere is fully typed even though the module itself is untyped JavaScript.

Example: Declaring a Module API

typescript
declare module "legacy-math" {
  export function add(a: number, b: number): number;
  export function subtract(a: number, b: number): number;
}
console.log("Module API declared for untyped JS module legacy-math");

Declaring a Class API

Declaring a class's public API mirrors declaring an interface but also captures constructor parameters and any static members, letting consumers new up and type-check instances of a class implemented elsewhere.

Example: Declaring a Class API

typescript
declare class Logger {
  constructor(prefix: string);
  log(message: string): void;
  static instance: Logger;
}
console.log("Class API declared: constructor, instance method, static member");

Keeping Declarations Accurate

Because a .d.ts file has no connection back to the real implementation, keeping it accurate means updating it by hand whenever the underlying JavaScript's actual behavior changes — an out-of-date declaration silently lies to the type checker.

Example: Keeping Declarations Accurate

typescript
// If the real JS function later adds a parameter,
// this declaration must be updated by hand to match:
declare function sendEmail(to: string, subject: string): void;
console.log("Out-of-date .d.ts files silently lie to the type checker");
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.