# Declaration Files (.d.ts)

> Typing pure JavaScript code.

Subject: TypeScript | Lesson 49 of 54 | 3 min read
Interactive lesson: https://codewithanimation.in/typescript/declaration-files-dts
Previous: [Module Resolution](https://codewithanimation.in/typescript/module-resolution.md) | Next: [Typing the DOM](https://codewithanimation.in/typescript/typing-the-dom.md)

## The Type Overlay

A declaration file (`.d.ts`) is a TypeScript file that contains only type information—no actual executable JavaScript code.

It acts as a "type overlay" or a blueprint that describes the shape of pure JavaScript code to the TypeScript compiler.

## The Untyped Wild West

If you install a pure JavaScript library (like an old version of `lodash`) and try to import it, TypeScript will throw an error because it has no idea what functions exist inside that library.

By creating a `.d.ts` file, you can "ambiently declare" the types for that library, allowing you to use it safely in TypeScript.

## Syntax

```typescript
// In a file named 'global.d.ts'

// 1. Typing a missing JS module
declare module "untyped-lib" {
  export function doMagic(input: string): number;
}

// 2. Typing a global window variable
declare global {
  interface Window {
    ANALYTICS_ID: string;
  }
}
```

## Common mistake: DefinitelyTyped

Writing `.d.ts` files for massive libraries by hand is excruciating.

Thankfully, the community maintains the `DefinitelyTyped` repository. If a package lacks types, you can usually run `npm install -D @types/package-name` to download a pre-written `.d.ts` file.

## Tip: No Implementation Allowed

You cannot write actual code logic inside a `.d.ts` file (like `const x = 5;`). The compiler will strictly enforce that only type definitions exist there.

## Try it: Try it

See how an ambient declaration file bridges the gap between an untyped JavaScript module and a strict TypeScript consumer.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/declaration-files-dts

## Check yourself

### Question 1

What is the primary purpose of a `.d.ts` file?

- A. To optimize the JavaScript compilation output.
- B. To provide type definitions for existing, untyped JavaScript code.
- C. To store global configuration variables like API keys.

Correct answer: B

Declaration files are blueprints. They contain zero executable logic and exist solely to tell the TypeScript compiler the shape (types, functions, classes) of JavaScript code that was written outside of TypeScript.

## Remember this

- `.d.ts` files contain ONLY types. No executable code.
- Use `declare module "name"` to type a missing NPM package.
- Use `declare global` to add types to the `window` object.
- Always check for `@types/package-name` before writing your own!
