Course contentsShow
← TypeScript
Lesson 1130 of 1,79626. Modules in TypeScriptFree lesson

Typing Third-Party Libraries

Creating declaration files for untyped npm packages in your project or node_modules/@types.

Typing Third-Party Libraries

What you'll learn: How to create declaration files for npm packages that lack type definitions.

The Problem: Untyped Dependencies

When you install a third-party npm package, TypeScript needs type information to provide safety and autocomplete. Many JavaScript packages don't ship with built-in types. When this happens, TypeScript treats their exports as any, losing all type safety.

You've already learned about using @types/* packages from DefinitelyTyped. But what if a package has no community types available?

Creating Your Own Declaration Files

You have two approaches to typing untyped libraries:

1. Project-Local Declaration Files

Create a .d.ts file anywhere in your project (commonly in a types/ folder or next to where you use the library). Use declare module to tell TypeScript about the package's shape:

// types/my-untyped-lib.d.ts
declare module 'my-untyped-lib' {
  export function doSomething(value: string): number;
  export const VERSION: string;
}

Now when you import this package, TypeScript knows its structure.

2. node_modules/@types Folder

For a more "official" feel, create node_modules/@types/my-untyped-lib/index.d.ts. TypeScript automatically discovers this location. However, this gets wiped out when you reinstall dependencies, so it's mainly useful for quick testing.

Think of It Like a Translator

Imagine a third-party library is a foreign book. The JavaScript code works (the story exists), but TypeScript can't read it. A declaration file is like a detailed table of contents and glossary—it doesn't change the book's content, but it helps TypeScript understand what's available and what each function expects.

Key Takeaway: When an npm package lacks types, you can write your own .d.ts declaration file using declare module to define its exports, giving you type safety even for untyped JavaScript libraries.