Sub topic 6
What `"strict": true` Turns On
Assume you know basic TypeScript types, functions, and interfaces. This chapter focuses on how the strict compiler option changes type checking. It does not change the JavaScript runtime. It makes the compiler report more situations where your code could fail.
`strict` is an umbrella option
In tsconfig.json, "strict": true enables a group of related checks:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true
}
}The main checks are:
| Check | What it catches |
|---|---|
| `noImplicitAny` | Values whose type would silently become `any` |
| `strictNullChecks` | Unsafe use of `null` and `undefined` |
| `strictPropertyInitialization` | Class properties that may remain unassigned |
| `strictFunctionTypes` | Unsafe function parameter assignments |
| `strictBindCallApply` | Incorrect arguments passed through `bind`, `call`, or `apply` |
| `noImplicitThis` | A `this` value with no reliable type |
| `useUnknownInCatchVariables` | Unsafe assumptions about caught errors |
| `alwaysStrict` | Emission and parsing using JavaScript strict mode |
The exact set can grow in future TypeScript versions. You can override one member after enabling the umbrella option:
{
"compilerOptions": {
"strict": true,
"noImplicitAny": false
}
}This keeps the other strict checks enabled while allowing implicit any. Treat this as a migration step, not a permanent safety improvement.
Fixing errors instead of silencing them
noImplicitAny requires you to describe a parameter when TypeScript cannot infer its type. strictNullChecks treats null and undefined as separate types, so you must check them before using a value.
function double(value: number): number {
return value * 2;
}
function lengthOf(text: string | null): number {
if (text === null) {
return 0;
}
return text.length;
}
function formatUser(name: string | undefined): string {
return name === undefined ? "Anonymous" : name.toUpperCase();
}
console.log(double(4));
console.log(lengthOf(null));
console.log(formatUser(undefined));The check in lengthOf is called narrowing. TypeScript narrows text from string | null to string inside the branch where it knows that text is not null.
What strict does not include
Some useful checks are separate options. For example, noUncheckedIndexedAccess adds undefined to values read from an array or object index:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}Enable these extra checks deliberately. They catch more defects, but they can require additional checks in existing code.
Exercise
If a parameter causes an implicit any error under strict mode, what is the usual fix?
Show answer
Add an appropriate type annotation, such as changing function double(x) to function double(x: number): number.