Sub topic 1
TypeScript Modules and Declaration Files
Prerequisites
You should know basic TypeScript types, interfaces, and functions. You should also be familiar with JavaScript import and export statements, tsc, and package.json.
Scripts versus modules: what makes a file a module
A TypeScript file is a module when it contains a top-level import or export. Its variables have module scope, so they are private unless exported.
A file without import or export is a script. Its declarations can be placed in the global scope and may conflict with declarations from other script files. Add export {} when a file should be treated as a module but has nothing to export.
// settings.ts
export const theme = "dark";
// main.ts
import { theme } from "./settings.js";
console.log(theme);The .js extension in the import is intentional for Node.js ES modules. TypeScript checks the .ts source file, but Node.js runs the emitted .js file.
Exporting and importing values
Named exports use names chosen by the exporting module. A default export represents the module’s primary value. A namespace import groups all exports under one object.
// math.ts
export function add(a: number, b: number) {
return a + b;
}
export default function multiply(a: number, b: number) {
return a * b;
}
// main.ts
import multiply, { add } from "./math.js";
import * as math from "./math.js";
console.log(add(1, 2));
console.log(multiply(2, 3));
console.log(math.add(4, 5));Type-only imports and exports
Use import type when an import is needed only by the type checker. TypeScript erases it from JavaScript output. Use export type for types that other modules may use.
// user.ts
export interface User {
id: number;
name: string;
}
// profile.ts
import type { User } from "./user.js";
export function showUser(user: User): string {
return user.name;
}CommonJS versus ES modules in Node.js
ES modules use import and export. CommonJS uses require and module.exports. Node.js determines the format from configuration, including the package’s "type" field and file extensions such as .mjs and .cjs.
Use one module format consistently within an application. TypeScript’s module: "nodenext" follows Node.js rules and helps reveal incompatible imports.
// tsconfig.json
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true
}
}Exercise
What makes a TypeScript file a module, and why should a value be exported?
Show answer
A top-level import or export makes it a module. A value must be exported before another module can import and use it.