Tutorials / TypeScript: Beginner to Advanced / Modules, type imports and declaration files

Modules, type imports and declaration files

15 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

Modules in TypeScript

TypeScript uses the same ES module syntax as modern JavaScript. Any file with a top-level import or export is a module, and its names are private unless exported. A file with neither is a script, and its declarations become global, which is rarely what you want. If you have a file with no imports or exports, add export {} to make it a module.

You can export types and values in the same way:

// models.ts
export interface User {
  id: number;
  name: string;
}

export type Role = "admin" | "member";

export function createUser(name: string): User {
  return { id: Date.now(), name };
}
// app.ts
import { createUser } from "./models";
import type { User, Role } from "./models";

const user: User = createUser("Sara");
const role: Role = "admin";
console.log(user.name, role);

import type

Notice the second import. import type brings in a name that is used only as a type, and the compiler removes it completely from the output. Importing a type with a regular import also works in most setups, but the explicit form has real benefits:

  • It makes clear to the reader and to the tools that no runtime code is needed.
  • It avoids accidental circular imports at runtime.
  • It is required with the verbatimModuleSyntax or isolatedModules options for some cases, since a tool that processes one file at a time cannot know whether an imported name is a type.

You can also mix them in one statement:

import { createUser, type User } from "./models";

I recommend turning on verbatimModuleSyntax in new projects. The compiler then makes you write import type where it is needed, and the output matches what you wrote.

Re-exporting

An index.ts file can gather the public parts of a folder:

// models/index.ts
export * from "./user";
export * from "./product";
export type { Order } from "./order";

Other code imports from ./models and does not need to know the file layout. Keep these barrel files small, since huge barrels can slow down compilation and bundling.

Module resolution and file extensions

moduleResolution tells the compiler how to find an imported file. With Bundler, you can write "./models" with no extension, because your bundler resolves it. With NodeNext, which matches how Node's ES modules work, you must write the extension that will exist at runtime, so a TypeScript file models.ts is imported as "./models.js". This looks strange at first. It is correct, because the compiled file is the .js file. If you get "Cannot find module" errors, check this option and the extension first.

Declaration files

A .d.ts file contains only types and no code. It describes the shape of JavaScript that exists somewhere else. When you compile a TypeScript library, the declaration: true option produces one .d.ts file for each source file, so that other TypeScript users get types for your package.

// math.d.ts
export declare function add(a: number, b: number): number;
export declare const PI: number;

The declare keyword says "this exists at runtime, trust me, and here is its type".

Types for packages: @types

Many popular JavaScript packages were written without types. The community keeps their definitions in the DefinitelyTyped project, published as @types/... packages:

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

TypeScript finds them automatically. If you import a package and see "Could not find a declaration file for module 'x'", look for @types/x. Newer packages ship their own types, so you will not need a separate package for them. @types/node is the most common one, as it describes Node's built-in modules, process and Buffer.

Describing a module that has no types

When a package has no types at all, you can write a tiny declaration yourself. Create a file such as src/types/untyped-lib.d.ts:

declare module "untyped-lib" {
  export function slugify(text: string): string;
}

Now import { slugify } from "untyped-lib" is fully typed. For a quick start, you can declare the module with no body (declare module "untyped-lib";). Every import from it is then any, so treat this as a temporary step.

Global declarations

Sometimes a script adds something to the global scope, like a variable that your HTML page defines. Tell TypeScript about it:

// globals.d.ts
declare const APP_VERSION: string;

interface Window {
  analytics?: { track(event: string): void };
}

Adding to the existing Window interface works because of declaration merging: interfaces with the same name are combined. Inside a module file, you need declare global { ... } around such declarations.

Importing JSON and assets

To import a .json file, turn on resolveJsonModule:

import settings from "./settings.json";
console.log(settings.port);   // typed from the JSON

For images and CSS files imported by a bundler, write a one-line declaration so the import is accepted:

declare module "*.svg" {
  const url: string;
  export default url;
}

A quick check that runs

The following single-file example uses a type-only export and a generic function. It stands in for what would be two files in a real project.

export interface Item {
  id: number;
  label: string;
}

export function byId<T extends { id: number }>(items: T[]): Map<number, T> {
  return new Map(items.map(item => [item.id, item]));
}

const items: Item[] = [
  { id: 1, label: "one" },
  { id: 2, label: "two" },
];

const lookup = byId(items);
console.log(lookup.get(2)?.label);   // two

Common mistakes

  • **Missing .js extension under NodeNext.** The compiler tells you, but the fix feels wrong at first.
  • **Importing a type as a value with isolatedModules on.** Use import type.
  • **Writing a .d.ts file in a place include does not cover.** The compiler will not see it.
  • **Declaring a module as any and forgetting it.** Replace it with real types soon.
  • Barrel files that import everything. They hurt build time and can create import cycles.
  • **Putting types in @types packages in dependencies for apps.** They belong in devDependencies.

Try it yourself

  1. Split an example from an earlier lesson into models.ts and app.ts. Use import type for the interfaces.
  2. Install @types/node and use process.argv in a file. Remove the package and see the error.
  3. Write a declare module for an imaginary package tiny-colour that exports a function hex(r: number, g: number, b: number): string.
  4. Add resolveJsonModule, create a config.json, and import it.
typescript
export interface Item {
  id: number;
  label: string;
}

export function byId<T extends { id: number }>(items: T[]): Map<number, T> {
  return new Map(items.map(item => [item.id, item]));
}

const items: Item[] = [
  { id: 1, label: "one" },
  { id: 2, label: "two" },
];

const lookup = byId(items);
console.log(lookup.get(2)?.label);   // two

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account