Third-Party Library Types and Declarations

Learn to use community type packages, understand .d.ts files, write declarations, and work with libraries that do not provide types.

🎯 Introduction

Understanding third-party library types improves your frontend development experience!

Frontend projects often use libraries such as lodash and axios. Some libraries do not include type definitions, or provide incomplete definitions, which can make them harder to use with TypeScript.

By the end of this article, you will be able to:

  • Use third-party library types more effectively to improve safety and development efficiency
  • Understand and write declaration files for libraries without types
  • Resolve common third-party type issues in real projects

📦 Using Community Type Packages Such as @types/lodash

Many popular JavaScript libraries have community-maintained types, commonly published on npm as @types/xxx packages.

For example, to use lodash with type support, run:

npm install lodash
npm install -D @types/lodash

@types/lodash is a declaration package maintained by the DefinitelyTyped community. It provides detailed type definitions for lodash.

Why Install @types Packages?

TypeScript can infer some types from JavaScript, but it needs type information to understand third-party APIs reliably. If a library does not provide its own .d.ts files, installing its @types package gives the editor and compiler function signatures, parameter types, and return types.

How Can I Find the Matching @types Package?

Visit the DefinitelyTyped repository or search npm for packages beginning with @types/. Most popular libraries have types maintained by their authors or the community.

With Yarn, use yarn add -D @types/lodash, which is equivalent to the npm command.

📝 What Is a .d.ts Declaration File?

A .d.ts file, or declaration file, describes the structure of JavaScript code to TypeScript. It contains type information rather than executable implementations.

Think of a manual that says “pressing this button turns on the light” without containing the actual button or light. A .d.ts file serves the same purpose: it tells TypeScript what a library looks like and which APIs it exposes.

Main Purposes:

  • Provide type information for JavaScript libraries without types
  • Let TypeScript check that you use a library correctly
  • Enable editor suggestions to improve development efficiency

Basic .d.ts File Structure

// math-lib.d.ts
declare module 'math-lib' {
    export function add(a: number, b: number): number;
    export function subtract(a: number, b: number): number;
}

This declaration tells TypeScript that math-lib exports two functions, add and subtract.

.d.ts files are often published alongside JavaScript libraries, but you can also write them locally in your project.

✍️ Writing Your First Declaration File

Small or custom JavaScript libraries may not include declarations. In that case, you can write your own .d.ts file.

Step 1: Identify the Module Name and Exports

Suppose a library named my-utils.js exports a function called formatDate.

// my-utils.js
function formatDate(date) {
    return date.toISOString();
}
module.exports = { formatDate };

Step 2: Create the Corresponding my-utils.d.ts File

declare module 'my-utils' {
    export function formatDate(date: Date): string;
}

Place it in the project's types folder or root directory, and configure "typeRoots": ["./types", "./node_modules/@types"] in tsconfig.json.

Step 3: Import It as Usual

import { formatDate } from 'my-utils';

const str = formatDate(new Date());

TypeScript can now recognize the parameter and return types of formatDate.

Common Declaration Syntax

  • declare module 'xxx' {}: Declares a module
  • export function foo(): void: Declares an exported function
  • export interface Foo {}: Declares an interface
  • export type Bar = string | number: Declares a type alias
Start with simple function declarations, then progress to interfaces and more complex types.

🔧 Practical Solutions for Libraries Without Type Declarations

Suppose you want to use cool-lib, but it has no type declarations. Importing it directly produces an error:

import { coolFunc } from 'cool-lib'; // Error: no declaration file found for module 'cool-lib'

Solution 1: Write a Custom Declaration File

Create types/cool-lib.d.ts in your project:

declare module 'cool-lib' {
    export function coolFunc(arg: string): number;
}

Make sure "typeRoots" in tsconfig.json includes ./types.

Solution 2: Use any as a Temporary Workaround

If you do not yet know the types, start with:

declare module 'cool-lib' {
    const coolFunc: any;
    export { coolFunc };
}

Using any long term sacrifices type checking, so replace it with accurate types as soon as possible.

Solution 3: Use Ambient Declarations for Global Variables

Some libraries attach their APIs directly to global variables, which requires a different declaration approach.

declare global {
    interface Window {
        myGlobalLib: {
            doSomething(): void;
        };
    }
}

You can then call window.myGlobalLib.doSomething() directly in your code.

Tip

If you are unsure of a type when writing declarations, start with a broad type such as any or unknown, then refine it as you learn more about the API.


❓ Questions and Answers

Q1: Why install an @types package?

It provides a third-party library's type definitions so TypeScript can understand its API, helping reduce errors and improve development efficiency.

Q2: Can a .d.ts file contain implementation code?

No. A .d.ts file contains type declarations, not JavaScript implementations.

Q3: Can I use a third-party library without type declarations?

Yes, but TypeScript may report errors or be unable to check its types. Write your own declarations or install an available @types package.


🧪 Practice Exercises

Exercise 1: Declare Types for a Simple Untyped Library

Suppose string-utils.js exports a function capitalize(str). Complete the corresponding .d.ts declaration template.

// string-utils.d.ts
declare module 'string-utils' {
    // Add the declaration here
}

Exercise 2: Import and Use an Untyped Library

  • Create a declaration file for a library named math-tools that exports multiply(a: number, b: number): number
  • Import and call multiply without type errors
import { multiply } from 'math-tools';

const result = multiply(3, 4);
console.log(result);

🎉 You now understand third-party library types, .d.ts files, custom declarations, and approaches to untyped libraries! You can use third-party libraries more confidently in your TypeScript projects.