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 };