TypeScript Tutorial · TypeScript in Practice · Lesson 24 of 25

TypeScript Modules and Declaration Files

import and export types, .d.ts files and @types packages.

Create a free account to save this page, take notes and track your progress. Sign in

Exporting and importing types

Types are exported and imported just like values. import type makes it explicit that only types are imported (they disappear from the JavaScript output):

// models.ts
export interface User { id: number; name: string }
export type Role = "admin" | "member";
export function isAdmin(role: Role): boolean { return role === "admin"; }
// app.ts
import { isAdmin } from "./models.js";
import type { User, Role } from "./models.js";

Declaration files (.d.ts)

A .d.ts file contains only types — it describes JavaScript code that has no types of its own. Libraries either ship their own declarations or have community types on npm:

npm install --save-dev @types/node @types/express

You can also declare types for a global or a module yourself:

// globals.d.ts
declare const __APP_VERSION__: string;
declare module "legacy-lib" {
  export function slugify(text: string): string;
}
Example 1Try it yourself
// In one file, "export" and "import type" look like this; here we inline the module.
interface Money { cents: number; currency: "USD" | "EUR" }
const format = (m: Money): string => `${(m.cents / 100).toFixed(2)} ${m.currency}`;

const total: Money = { cents: 2599, currency: "EUR" };
console.log(format(total));

Output

25.99 EUR

Test yourself

Where do community type definitions for JavaScript libraries live on npm?

  1. @typescript/<package>
  2. @types/<package>
  3. <package>-types
  4. @dt/<package>
Show answer

Answer: @types/<package>

Was this page helpful?