The compiler and runtime
Enable strict checking
Turn on the family of strict compiler checks and fix the contracts they reveal instead of weakening the project globally.
The single most useful line in a tsconfig.json is this one:
{
"compilerOptions": {
"strict": true
}
}
strict is not one check. It is a switch that turns on a whole family of them: noImplicitAny, strictNullChecks, strictFunctionTypes, strictPropertyInitialization, and a few more. Most of what this course has called “TypeScript catches this” only happens with strict on.
What it catches
Without strict checking, an untyped parameter quietly becomes any. With it, the compiler refuses:
function uppercase(value) {
return value.toUpperCase()
}
Parameter 'value' implicitly has an 'any' type.
It also stops you from touching a value that might be missing:
function shout(value: string | undefined) {
return value.toUpperCase()
}
'value' is possibly 'undefined'.
Both errors point at real problems. The first function accepts anything and crashes on a number. The second crashes on undefined. Strict mode moves those crashes from runtime to your editor.
Fix the contract, not the setting
When one of these errors shows up, the temptation is to turn the check off, or to add any, !, or an as. Don’t. Fix the contract instead.
Give uppercase() its real parameter type, value: string. Narrow shout() with if (value === undefined) return '' before the method call. If the value came from JSON or an environment variable, validate it at the boundary, the way we do in the runtime validation lesson.
Each fix is small, and each one removes a crash that was already in your program. The error only made it visible.
Existing projects
New projects should start strict. There is no cheaper moment to fix these errors than before the code exists.
On an existing JavaScript-heavy codebase, flipping strict on can produce hundreds of errors at once. Enable the checks one at a time in that case, starting with noImplicitAny, then strictNullChecks. Keep a short list of temporary exceptions and shrink it every week. The goal is still "strict": true with no exceptions.
One more thing. TypeScript can add new checks under the strict umbrella in future versions, so a compiler upgrade can surface new errors. Run npx tsc --noEmit right after upgrading, before anything else.
Try this: enable strict, add one untyped parameter and one possibly undefined value, then fix both without any, !, or an assertion.
Lesson completed