Lesson 12
20 min
import / export, @types packages, typing the DOM and API data.
Definition
A module is a code file that keeps its elements private by default and explicitly chooses what it shares with other files. A library is a set of already-written modules, published by other developers, that you install to reuse their work.
A real program never fits in a single file. Splitting the code into modules makes each file shorter and easier to read, avoids name conflicts and lets you reuse the same code in several places. And rather than writing everything yourself, you can rely on thousands of libraries, as long as you know how to type them.
As soon as a project grows, you spread the code across several files. In TypeScript, as in modern JavaScript, every file that contains an import or an export is a module. Types, interfaces and functions can all be exported.
export interface User {
id: number;
name: string;
}
export function createUser(name: string): User {
return { id: Date.now(), name };
}
export default class UserDirectory {
private list: User[] = [];
add(u: User): void {
this.list.push(u);
}
}import UserDirectory, { createUser } from "./user";
import type { User } from "./user";
const directory = new UserDirectory();
const lea: User = createUser("Lea");
directory.add(lea);import type indicates that you are importing only a type: this import disappears completely from the generated JavaScript.

export function ...): a file can have as many as it wants, and you import them between curly braces with their exact name.export default ...): only one per file, imported without curly braces under whatever name you like.Many teams prefer named exports, because the editor can then suggest the import automatically and the name stays the same everywhere. Default exports are mostly found in framework components.
import { createUser as newUser } from "./user";
import * as tools from "./user";
const tom = newUser("Tom");
const sara = tools.createUser("Sara");When a folder contains several modules, you often create an index.ts file that re-exports them. Other files then have only one path to import, and you can reorganize the inside of the folder without breaking the rest of the project.
export * from "./user";
export * from "./task";
export type { Settings } from "./settings";
// In another file:
// import { createUser, Task } from "./models";Many libraries are written in TypeScript and ship with their types: nothing more to do. For plain JavaScript libraries, the community often publishes the types in a separate package named @types/library-name.
npm install lodash
npm install --save-dev @types/lodash
# To use Node.js modules (fs, path...)
npm install --save-dev @types/node
These packages contain declaration files, whose extension is .d.ts. They contain no executable code: only the description of the library's types. The @types/lodash package is installed with --save-dev because it is only used during development, not when the program runs.
// Describe the types of a library that has none
declare module "old-lib" {
export function compute(a: number, b: number): number;
}A classic import runs when the program starts. To load a module only when it becomes necessary (for example after a click), you use the dynamic import: import() returns a promise, and TypeScript keeps the types of the loaded module.
async function showChart() {
const { draw } = await import("./chart");
draw([1, 2, 3]); // draw is correctly typed
}This technique lightens a page's initial load: the code of a rarely used feature is only downloaded on demand.
TypeScript knows the browser's types. Since an element searched for in the page may not exist, querySelector returns a type that includes null. You therefore have to check it, and specify the type of element you expect.
const field = document.querySelector<HTMLInputElement>("#name");
if (field) {
field.addEventListener("input", () => {
console.log(field.value.toUpperCase());
});
}
const button = document.querySelector("button");
button?.addEventListener("click", (event: MouseEvent) => {
console.log("Click at", event.clientX, event.clientY);
});Without the <HTMLInputElement> specification, TypeScript wouldn't know that the element is an input field and would refuse to access its value property. The DOM types come with TypeScript: you have nothing to install to use them. The types follow the browser's hierarchy: an input field is a special case of an HTML element, itself a special case of an element, hence names like HTMLInputElement or HTMLButtonElement.
Data coming from an API is not checked by TypeScript at runtime: types no longer exist at that stage. You describe the expected shape, but it remains your responsibility to make sure the response respects it.
interface Task {
id: number;
title: string;
done: boolean;
}
async function loadTasks(): Promise<Task[]> {
const response = await fetch("https://example.com/api/tasks");
const data: Task[] = await response.json();
return data;
}Warning
Annotating an API response with an interface doesn't validate it: it is a promise you make to TypeScript. To really validate external data, libraries like Zod exist.
While waiting to use such a library, you can already do a minimal check with unknown: you receive the data without trusting it, then test its shape before processing it.
function isTask(value: unknown): value is Task {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
"done" in value
);
}The tsconfig.json file placed at the root of the project sets the compiler's behavior. A few options come up almost every time: the level of JavaScript produced, the module system, and above all strict mode.
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"outDir": "dist"
},
"include": ["src"]
}The target option chooses the version of JavaScript produced, module the module system, outDir the folder where the compiled files are written, and include the list of folders to compile. The strict option enables all the rigorous checks at once, notably the rejection of null and undefined in other types.
To migrate an existing project, start by renaming one file from .js to .ts, fix the reported errors, then move on to the next. Don't try to type everything perfectly on the first day: every converted file already improves the safety of the whole.
These best practices reinforce one another: strict mode reveals fragile spots, unknown forces you to check uncertain data, and inference keeps the code light. A team that applies them all gets safer code without making it heavier.
any or reports an error.import or export is a module.import type imports a type without leaving anything in the final JavaScript.@types/... packages provide the types of JavaScript libraries.Exercise
types.ts file that exports aTask interface, and a tasks.ts file that imports it and exports functions to add, complete and list tasks.Going further