Course contentsShow
← TypeScript
Lesson 1147 of 1,79627. Declaration FilesFree lesson

Typing Third-Party Libraries

Write declaration files for untyped npm packages by creating a matching .d.ts in your project or @types.

Typing Third-Party Libraries

You'll learn how to add type safety to npm packages that don't include their own TypeScript definitions.

What Problem Are We Solving?

Not every JavaScript package on npm ships with TypeScript types. When you install a library like lodash or an older utility package, TypeScript might warn you that it can't find type declarations. Without types, you lose autocomplete, type checking, and IntelliSense — essentially falling back to plain JavaScript.

The good news: you can write your own declaration files to bridge this gap, even for libraries you don't maintain.

Two Approaches to Typing Untyped Libraries

1. Installing from @types

Many popular libraries have community-maintained types available through DefinitelyTyped. Install them alongside the package:

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

import _ from 'lodash';

const result = _.chunk([1, 2, 3, 4], 2);
// TypeScript now knows result is number[][]

If @types/packagename exists, this is the easiest solution.

2. Writing Your Own Declaration File

When no @types package exists (or it's incomplete), create a .d.ts file in your project:

// src/types/untyped-library.d.ts
declare module 'untyped-library' {
  export function doSomething(input: string): number;
  export const VERSION: string;
}

Now you can import and use the library with full type safety:

// src/app.ts
import { doSomething, VERSION } from 'untyped-library';

const result = doSomething("hello"); // result: number
console.log(VERSION.toUpperCase()); // VERSION: string

The Matching Pattern

TypeScript looks for a .d.ts file matching the module name you're importing. Place it anywhere TypeScript scans (usually in your src directory or a dedicated types folder). Make sure your tsconfig.json includes it.

When to Use Each Approach

  • Use @types when available — it's maintained by the community and kept up-to-date
  • Write your own for internal libraries, custom tools, or when @types doesn't exist
  • Start minimal — only type the functions you actually use, then expand as needed

Key Takeaway: You can add type safety to any untyped npm package by either installing @types/package-name or creating a matching .d.ts file with declare module in your project.