Modules, type imports and declaration files
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- 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
verbatimModuleSyntaxorisolatedModulesoptions 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
.jsextension underNodeNext.** The compiler tells you, but the fix feels wrong at first. - **Importing a type as a value with
isolatedModuleson.** Useimport type. - **Writing a
.d.tsfile in a placeincludedoes not cover.** The compiler will not see it. - **Declaring a module as
anyand 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
@typespackages independenciesfor apps.** They belong indevDependencies.
Try it yourself
- Split an example from an earlier lesson into
models.tsandapp.ts. Useimport typefor the interfaces. - Install
@types/nodeand useprocess.argvin a file. Remove the package and see the error. - Write a
declare modulefor an imaginary packagetiny-colourthat exports a functionhex(r: number, g: number, b: number): string. - Add
resolveJsonModule, create aconfig.json, and import it.
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