Chapter 1 · Practice 1 of 6
Keep strict on and add the checks strict leaves out
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:
| Option | What it catches |
|---|---|
noUncheckedIndexedAccess | Reading arr[i] or record[key] gives T | undefined, so you handle missing entries |
exactOptionalPropertyTypes | An optional property cannot be set to undefined unless its type says so |
noImplicitOverride | A subclass method that overrides a base method must say override |
noFallthroughCasesInSwitch | A 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
stricton and treat every strict error as a real question about your data - Add
noUncheckedIndexedAccessandnoImplicitOverrideto new projects from day one - Enable new checks in a branch and fix errors one folder at a time
Avoid
- Setting
strict: falseor individual strict flags tofalseto silence errors - Sprinkling
!after every indexed read oncenoUncheckedIndexedAccessis on
Example
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true
}
}