DevAcademy
LearnTypeScriptDeclaration Files
AdvancedTypeScript

Declaration Files

Learn how .d.ts files describe the types of plain JavaScript code, and how TypeScript finds them for third-party packages.

Reading Time

16 min

Lesson

Lesson 27 of 30

What is a Declaration File?

A declaration file (ending in .d.ts) contains only type information — no actual implementation code. It describes the shape of existing JavaScript so TypeScript can type-check code that uses it.

A Simple Declaration File

// math-utils.d.ts
export function square(n: number): number;
export function cube(n: number): number;

Why Declaration Files Exist

Countless JavaScript libraries were written before TypeScript existed, and many still ship as plain JavaScript. Declaration files let TypeScript understand and type-check calls into that untyped code, without the library itself needing to be rewritten.

The DefinitelyTyped Project

For popular packages that don’t ship their own types, the community maintains type definitions in the @types npm scope, sourced from the DefinitelyTyped repository.

Installing Community Types

npm install lodash
npm install --save-dev @types/lodash

Generating Declaration Files from Your Own Code

The declaration compiler option automatically generates .d.ts files alongside your compiled JavaScript, so consumers of your own published package get full type support.

Emitting Declarations

{
  "compilerOptions": {
    "declaration": true,
    "outDir": "dist"
  }
}

Ambient Declarations for Global Values

A declare statement describes a value that exists at runtime but wasn’t defined through a normal TypeScript declaration — commonly used for global variables injected by a script tag or build tool.

Declaring a Global Value

// globals.d.ts
declare const APP_VERSION: string;

// usage anywhere in the project, no import needed
console.log(APP_VERSION);

How TypeScript Finds Types for a Package

TypeScript checks, in order: the package’s own bundled .d.ts files (referenced via its "types" field in package.json), then a matching @types/package-name package, before finally falling back to implicit any if strict mode allows it.

Best Practice

Before writing a custom declaration file for a third-party package, check whether @types/package-name already exists — most popular packages are already covered.

Interview Questions

Quick Quiz

1. What does a .d.ts file contain?

2. What is DefinitelyTyped?

3. What does declare const APP_VERSION: string do?