TypeScript Modules and Declaration Files

TypeScript modules use the same import and export syntax as JavaScript ES modules, with extra support for exporting types. Declaration files (.d.ts) describe the types of JavaScript code that has no TypeScript source.

Exporting and Importing Types

You can export types, interfaces and values from the same file. import type imports only types and is fully erased from the output, which keeps bundles clean.

// models.ts
export interface Product { id: number; name: string; price: number }
export const formatPrice = (p: Product) => `${p.price.toFixed(2)}`;

// app.ts
import { formatPrice } from "./models.js";
import type { Product } from "./models.js";

const p: Product = { id: 1, name: "Rice", price: 12.5 };
console.log(formatPrice(p));
$12.50

Why .js in Import Paths?

With "module": "NodeNext", you write the extension of the compiled file (.js) even though the source is .ts, because Node resolves the output files. Bundler-based projects (Vite) usually use "moduleResolution": "bundler" and allow omitting extensions.

Using @types Packages

Many libraries ship their own types. For those that do not, the community publishes types in the DefinitelyTyped project as @types/<package>.

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

// now fully typed:
import { chunk } from "lodash";
console.log(chunk([1, 2, 3, 4, 5], 2));
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

Writing a Declaration File

If a library has no types at all, declare them yourself in a .d.ts file. A .d.ts contains only types, no implementation.

// types/tiny-slug.d.ts
declare module "tiny-slug" {
  export default function slugify(text: string, sep?: string): string;
}

// app.ts
import slugify from "tiny-slug";
console.log(slugify("Learn TypeScript Fast"));
learn-typescript-fast

Global Declarations

Use declare global to add properties to global objects, and declare const for values injected by a build tool. Environment variables in Vite are typed this way.

// env.d.ts
declare global {
  interface Window {
    analyticsId?: string;
  }
}
declare const __APP_VERSION__: string;
export {};

Frequently asked questions

What is a .d.ts file in TypeScript?

A declaration file that contains only type information. It describes the shape of JavaScript code so TypeScript can type-check code that uses it.

What does import type do?

It imports only type information, which is removed entirely from the compiled JavaScript. It avoids accidental runtime imports and helps tools like Vite.

How do I fix "Could not find a declaration file for module"?

Install the @types package if one exists, or add a .d.ts file with declare module "name" to describe the library yourself.