Modules and tooling¶
This lesson covers the module system, type-only imports, declaration files, and the parts of tsconfig.json you will touch most often.
ES modules¶
TypeScript supports the standard ES module syntax.
// math.ts
export function add(a: number, b: number): number {
return a + b
}
export const PI = 3.14159
Note
TypeScript allows import ... from './math.js' even when the source file is math.ts. The .js extension matches the emitted file and keeps the import valid at runtime.
Default and named exports¶
Type-only imports¶
Use import type when you only need the type at compile time.
These imports are erased from the emitted JavaScript.
Re-exports¶
Declaration files¶
A .d.ts file describes types for JavaScript code.
These are common when consuming untyped libraries or writing global types.
tsconfig.json in practice¶
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"exactOptionalPropertyTypes": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}
| Flag | Effect |
|---|---|
strict |
Enables the strongest common checks |
noImplicitAny |
Flags places where any is inferred |
noUnusedLocals |
Warns about unused variables |
exactOptionalPropertyTypes |
Distinguishes undefined from missing |
Path mapping¶
For larger projects, map import aliases.
Hands-on: split a project into modules¶
- In your project
src/folder, createutils.ts,user.ts, andmain.ts. - In
user.ts, exportinterface Userandfunction createUser(name: string): User. - In
utils.ts, exportfunction formatName(name: string): string. - In
main.ts, import the user and utility, create a user, and log a formatted name. - Use
import type { User } from './user.js'in a file that does not need the runtimecreateUserfunction. - Add
"noUnusedLocals": truetotsconfig.jsonand remove any unused variables the compiler reports.