Compiler Options That Matter
tsc --init lists well over a hundred options, and it is easy to feel you must understand them all. You do not. A handful decide almost everything about how your project is checked and what JavaScript comes out.
The rule
strict decides how hard it checks; target and module decide what it writes.
How hard it checks — strict. One switch that turns on a family of checks. The two you will feel most:
strictNullChecks—nullandundefinedare no longer silently allowed in every type. A function that might return nothing must say so, and callers must handle it.noImplicitAny— a value whose type cannot be inferred, like an unannotated parameter, is an error instead of quietly becomingany.
function findTask(tasks: Task[], id: number) {
return tasks.find(t => t.id === id); // Task | undefined
}
findTask(all, 3).title; // strict: error, the task may be undefinedWithout strict mode that last line compiles and crashes at runtime when no task matches.
What it writes — target and module.
target— the JavaScript version to output, such asES2022. With an older target, newer syntax is rewritten into older equivalents. It also picks a default set of built-in type declarations (lib), which decides whether methods likeArray.prototype.atare known to exist.module— the module system of the output, such asNodeNextfor modern Node.js orESNextfor bundlers.
Whether it writes at all.
noEmit— check only, write no files. Common when a bundler or runner produces the JavaScript and tsc is used purely as a checker.noEmitOnError— write nothing if there are type errors.
The shortcut
For any option, sort it into one of three questions: "How strict? What output? Output at all?" Most settings you will ever touch answer one of those.
How strict?
New project, so
"strict": truefrom day one. Turning it on later means fixing many errors at once.
A trap: target does not add missing features at runtime. Setting a new target lets you use Array.prototype.at in types, but if the environment running the code lacks it, the call still fails.
Drills
Answer fast — trust the rule.
Which option makes null and undefined stop fitting into every type?
With noImplicitAny on, what happens to function add(a, b) { return a + b; }?
A bundler builds your JavaScript and you only want tsc to check types. Which option fits?
What does the target option mainly control?
With strict on, tasks.find(...) returns Task | undefined. What must you do before reading .title?
Remember
- strict decides how hard it checks; target and module decide what it writes.
- Sort every option into: how strict, what output, output at all.
- Trap: a newer
targetdoes not make missing runtime features appear.
