Course outline · 0% complete

0/26 lessons0%

Course overview →

tsconfig Essentials and strict Mode

lesson 8-1 · ~11 min · 24/26

The project control panel

Real projects configure the compiler in one file, tsconfig.json, at the project root. A minimal, sane starting point:

{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "strict": true,
    "outDir": "dist"
  },
  "include": ["src"]
}
  • target: which JavaScript version to emit
  • module: how import/export is compiled
  • outDir: where compiled .js files go
  • include: which folders to compile
  • strict: the one that matters most

strict: true switches on a family of checks. The two headline members: noImplicitAny makes unannotated parameters an error instead of a silent any (remember lesson 1-3), and strictNullChecks makes null and undefined their own types instead of members of every type.

What strictNullChecks changes

Without it, this compiles and crashes. Tony Hoare, who introduced null references into programming languages in 1965, later called them his "billion-dollar mistake" — his estimate of what crashes exactly like this one have cost the industry:

const found: string = maybeFind(); // might be null!
console.log(found.toUpperCase());  // runtime crash

With strictNullChecks, a function that can fail must say so in its type, string | null, and callers must narrow before use, exactly the Unit 4 discipline:

if (found !== null) {
  console.log(found.toUpperCase());
}

Every new project should start with strict: true. Loosening a check later is easy, tightening one on a grown codebase means fixing hundreds of errors at once.

Code exercise · typescript

A search that honestly returns string | null, with the caller narrowing before use. Run it, then change the target to "linus" and check both paths.

Code exercise · typescript

Your turn. Write firstLongName(names: string[]): string | null that returns the first name with length >= 6, or null when none qualifies. Print both calls shown in the starter, using ?? "none found" (lesson 4-4) to close the null case in one step.

Quiz

Which flag makes an unannotated function parameter a compile error instead of silently typing it any?