JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
Prev
typescript
senior
declarations

How do you write declaration files for JavaScript libraries?

declaration-files
d.ts
ambient
augmentation
types
Quick Answer

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.

Detailed Explanation

Declaration File Basics:

  • .d.ts extension - types only, no runtime code
  • declare keyword for ambient declarations
  • No function bodies or initializers
  • Describes shape of JavaScript values

Types of Declarations:

  • Ambient modules: Declare external module types
  • Global: Declare global variables/types
  • Module augmentation: Extend existing modules
  • Global augmentation: Add to global scope

Best Practices:

  • Match runtime API exactly
  • Use JSDoc for additional documentation
  • Test with actual usage
  • Consider contributing to DefinitelyTyped

Code Examples

Basic declaration file
// 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 };

Resources

TypeScript - Declaration Files

docs

DefinitelyTyped

docs

Related Questions

How do TypeScript modules work and what's the difference between import types?

mid
modules

What are generics in TypeScript and how do you use them?

mid
generics
Previous
How do you handle complex generic constraints and variance in TypeScript?