Learn the concept
Declaration Files
Declaration files (.d.ts) provide type information for JavaScript code without implementation. They use 'declare' keyword for ambient declarations, support module augmentation for extending existing types, and global augmentation for adding to global scope.
Declaration File Basics:
.d.ts extension - types only, no runtime codedeclare keyword for ambient declarationsTypes of Declarations:
Best Practices:
// types/my-lib.d.ts
// Declare a function
declare function greet(name: string): string;
// Declare a variable
declare const VERSION: string;
// Declare a class
declare class MyClass {
constructor(options: MyClassOptions);
start(): void;
stop(): void;
readonly status: 'running' | 'stopped';
}
interface MyClassOptions {
name: string;
timeout?: number;
}
// Declare a namespace (for libraries with nested structure)
declare namespace MyLib {
function init(config: Config): void;
interface Config {
apiKey: string;
debug?: boolean;
}
namespace Utils {
function format(value: unknown): string;
}
}
// Export for module usage
export { greet, VERSION, MyClass, MyLib };Writing declaration files for untyped JavaScript libraries used in enterprise codebases
Creating precise .d.ts files for SDK distribution with conditional exports for ESM/CJS
Using ambient declarations and module augmentation to add custom properties to third-party types
Write comprehensive declaration files for a small untyped JavaScript utility library
Create a package with dual CJS/ESM support, separate .d.ts/.d.mts files, and correct package.json exports