Sub topic 3
Turning on Strict Mode
Assume you know JavaScript functions, objects, modules, and basic npm commands. TypeScript’s strict mode is a group of checks that catches unsafe code before it runs.
Strict mode
Enable strict checking in tsconfig.json:
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "NodeNext",
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}Strict mode includes checks such as noImplicitAny and strictNullChecks. The latter prevents code from using null or undefined as though a value always exists.
function firstLetter(text: string | undefined): string {
if (text === undefined) {
return "";
}
return text.charAt(0);
}Without the check, the compiler reports that text might be undefined.
Rebuilding on change
Use watch mode during development:
npx tsc --watchThe compiler checks changed files and emits updated JavaScript. Stop it with Ctrl+C.
Controlling emitted files
Choose whether tsc writes JavaScript with these options:
| Goal | Option |
|---|---|
| Type-check only | `"noEmit": true` |
| Keep output separate | `"outDir": "dist"` |
| Produce debugger mappings | `"sourceMap": true` |
| Block output when errors exist | `"noEmitOnError": true` |
Use npx tsc --noEmit in continuous integration when another tool builds the application.
Declarations and external types
A declaration file (.d.ts) describes JavaScript or library types without containing implementation. Set "declaration": true when publishing a TypeScript package. For JavaScript packages without declarations, install community types when available:
npm install --save-dev @types/nodeThe @types packages provide declarations for editors and the compiler.
Tools around `tsc`
Editors usually run the TypeScript language service for immediate diagnostics. Bundlers and runners such as Vite, esbuild, or tsx may transpile TypeScript themselves. In that setup, use npx tsc --noEmit for a separate full type check.
Incremental builds and project references
"incremental": true stores build information so later checks can skip unchanged work. Project references split a large codebase into projects. Referenced projects commonly use "composite": true, and tsc --build builds them in dependency order.
Exercise
Which command checks a project without producing JavaScript?
Show answer
npx tsc --noEmit