TypeScript Best Practices

Chapter 1 · Practice 1 of 6

Keep strict on and add the checks strict leaves out

From Compiler settings and TypeScript 7

Why it matters

Since TypeScript 6.0, strict defaults to true, and TypeScript 7.0 keeps that default. strict turns on a family of nine checks, including strictNullChecks, noImplicitAny, strictFunctionTypes and useUnknownInCatchVariables. Never turn it off to make errors go away: each error it reports is a place where a value can be something you did not plan for.

Several useful checks are not part of strict, so you have to enable them yourself:

OptionWhat it catches
noUncheckedIndexedAccessReading arr[i] or record[key] gives T | undefined, so you handle missing entries
exactOptionalPropertyTypesAn optional property cannot be set to undefined unless its type says so
noImplicitOverrideA subclass method that overrides a base method must say override
noFallthroughCasesInSwitchA non-empty case that falls into the next one

noUncheckedIndexedAccess is the one that finds the most real bugs, because code that reads from arrays and dictionaries usually assumes the entry exists. Turning it on in an existing codebase can produce many errors at once, so enable it in a branch and fix them folder by folder.

Do

  • Leave strict on and treat every strict error as a real question about your data
  • Add noUncheckedIndexedAccess and noImplicitOverride to new projects from day one
  • Enable new checks in a branch and fix errors one folder at a time

Avoid

  • Setting strict: false or individual strict flags to false to silence errors
  • Sprinkling ! after every indexed read once noUncheckedIndexedAccess is on

Example

JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true
  }
}