Labs ICT
โญ Pro Login

Declaration Files

Declaration files (.d.ts) are TypeScript's way of defining types for JavaScript libraries and external modules that don't have their own type definitions. You and I can write .d.ts files to make third-party libraries work seamlessly with TypeScript's type checking, providing autocomplete and error detection in our code.

External module declarations let you and me specify the public API surface of JavaScript libraries, defining function signatures, interfaces, and export statements. These files act as bridges between untyped codebases and your type-safe TypeScript applications, making integration with npm packages painless and predictable.

When you and I create proper declaration files, we enable TypeScript to catch type-related bugs in library interactions early. The result is more robust code that works smoothly with JavaScript libraries while maintaining the benefits of static typing throughout our development workflow.

Declaration File Example

You and I can write declaration files to add TypeScript support to JavaScript libraries. This example shows how to define a simple library with its public API surface, allowing TypeScript to understand the library's interface without modifying the original source code.

// lodash.d.ts (declaration file for JavaScript library)
declare function get(array: T[], index: number): T | undefined;
declare function set(array: T[], index: number, value: T): T[];
declare namespace Lodash {
  function map(array: T[], iteratee: (item: T, index: number) => R): R[];
}

// Using the declarations in TypeScript
import { get, set } from './lodash';

const numbers = [1, 2, 3];
const first = get(numbers, 0);
const updated = set(numbers, 0, 99);
console.log(first, updated);
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What are declaration files with .d.ts extension?