Classes and Modules · Lesson 14 of 17
TypeScript Modules, import type and .d.ts Files
Real projects are many files. TypeScript uses standard ES modules – import and export – with a few additions: you can import only types, and you can describe JavaScript code you didn't write with declaration files (.d.ts). This lesson covers how files talk to each other in a typed codebase.
In this lesson
- Named and default exports
import typeand why it matters- Barrel files and path aliases
.d.tsfiles,@typespackages anddeclare module
Exporting and importing
Any file with a top-level import or export is a module with its own scope. Types and values are exported the same way:
// src/models/course.ts
export interface Course {
slug: string;
title: string;
lessons: number;
}
export type Level = "beginner" | "intermediate" | "advanced";
export function levelFor(course: Course): Level {
return course.lessons < 10 ? "beginner" : course.lessons < 30 ? "intermediate" : "advanced";
}
export default class CourseCatalog {
private items: Course[] = [];
add(course: Course): void {
this.items.push(course);
}
get size(): number {
return this.items.length;
}
}
// src/main.ts
import CourseCatalog, { levelFor, type Course } from "./models/course.js"; // default + named
const ts: Course = { slug: "typescript", title: "TypeScript", lessons: 20 };
const catalog = new CourseCatalog();
catalog.add(ts);
console.log(catalog.size, levelFor(ts)); // 1 intermediate
Why "./course.js" in a .ts file?
With "module": "nodenext" (Node ESM), you write the extension of the file that will exist at run time, which is .js. TypeScript maps it back to course.ts. Bundler setups (Vite, Next.js, Angular CLI) use "moduleResolution": "bundler", where extensionless imports are fine.
import type
import type { Course, Level } from "./models/course.js"; // whole import is types only
import { levelFor, type Course as C } from "./models/course.js"; // inline: mix values and types
A type-only import is always removed from the emitted JavaScript. That matters because:
- it avoids loading a module at run time just for its types (and avoids accidental circular imports);
- single-file compilers (esbuild, SWC, Babel – used by Vite and Next.js) can't tell whether a name is a type, so they need you to mark it. The
verbatimModuleSyntaxoption makes TypeScript require it.
{
"compilerOptions": {
"verbatimModuleSyntax": true
}
}
Barrel files and path aliases
// src/models/index.ts – a "barrel" that re-exports a folder
export * from "./course.js";
export type { User } from "./user.js";
export { default as CourseCatalog } from "./course.js";
// elsewhere
import { CourseCatalog, type User } from "./models/index.js";
Path aliases avoid ../../../ chains. Note that paths only tells the type checker; your bundler or runtime needs the same mapping (Vite, Next.js and Angular read it automatically, or use Node's imports field):
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
}
}
Barrels: use with care
Barrels make imports tidy, but a big one can slow down builds and tests, because importing one name loads the whole folder. Keep them small, or import directly from the file in hot paths.
Declaration files (.d.ts)
A .d.ts file contains only types – no implementation. It describes JavaScript that exists somewhere else. You meet them in three ways:
Where types for a library come from
- Bundledthe package ships its own .d.ts (axios, zod, Next.js) – nothing to install
- DefinitelyTypedcommunity types: npm i -D @types/express, @types/node, @types/lodash
- Your owna .d.ts you write for an untyped library or a global variable
// src/types/legacy-analytics.d.ts – typing an old library with no types
declare module "legacy-analytics" {
export interface TrackOptions {
category: string;
value?: number;
}
export function track(event: string, options?: TrackOptions): void;
const version: string;
export default version;
}
// src/types/globals.d.ts – a global injected by a script tag
declare global {
interface Window {
__APP_CONFIG__: { apiUrl: string; release: string };
}
}
export {}; // makes this file a module so 'declare global' is allowed
Now import { track } from "legacy-analytics" is fully typed, and window.__APP_CONFIG__.apiUrl autocompletes. When you publish your own library, the declaration compiler option generates .d.ts files for you.
Typing environment variables
// src/env.d.ts – Node: make process.env keys known
declare global {
namespace NodeJS {
interface ProcessEnv {
DATABASE_URL: string;
NODE_ENV: "development" | "production" | "test";
}
}
}
export {};
This is declaration merging: your interface adds to the one from @types/node. It only describes the shape, though – it doesn't prove the variable is set. Validate at start-up (with a library such as zod) so a missing value fails immediately instead of deep inside a request.
Practice
Try it yourself
You use a JavaScript package
slugify-litethat exportsslugify(text: string, sep?: string): stringand has no types. Write the declaration.Show solution
// src/types/slugify-lite.d.ts declare module "slugify-lite" { export function slugify(text: string, sep?: string): string; }Why does
import typehelp with circular imports?Show solution
Type-only imports are erased, so at run time the two modules don't import each other at all – only the type checker sees the link.
Quick check
Does a .d.ts file produce any JavaScript?
No – it contains only type declarations.
Where do types for express come from?
From DefinitelyTyped: npm i -D @types/express.
What does verbatimModuleSyntax enforce?
That type-only imports are marked with type, so every tool can remove them safely.
Summary
- TypeScript uses ES modules; types and values are exported and imported the same way.
- import type is always erased – mark type-only imports, especially with Vite, Next.js or esbuild.
- .d.ts files describe JavaScript: bundled types, @types packages, or your own declare module / declare global.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.