Sub topic 6
What "strict": true turns on
This chapter assumes you can read a basic tsconfig.json, know what compilerOptions is, and have run npx tsc before. You should also be comfortable with type annotations, classes, and union types such as string | null.
What strict is
"strict": true is a single switch that turns on a group of related type-checking flags. It is not a separate check. The compiler expands it into the individual flags and applies each one.
The group is intentionally open-ended. When a new TypeScript version adds a check that the team considers part of "strict", it joins the group. Upgrading the compiler can therefore produce new errors in a project that already uses "strict": true. If you need stability, pin the TypeScript version in package.json.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true
}
}The flags inside the group
| Flag | What it catches |
|---|---|
| `noImplicitAny` | Variables and parameters whose type falls back to `any` silently |
| `strictNullChecks` | Using `null` or `undefined` where a real value is required |
| `strictFunctionTypes` | Unsafe assignment between function types with different parameter types |
| `strictBindCallApply` | Wrong arguments passed to `bind`, `call`, and `apply` |
| `strictPropertyInitialization` | Class properties that are never assigned |
| `noImplicitThis` | `this` with an implicit `any` type |
| `useUnknownInCatchVariables` | Treating a caught value as if it were always an `Error` |
| `alwaysStrict` | Missing strict-mode semantics in emitted JavaScript |
| `strictBuiltinIteratorReturn` | Treating the return value of built-in iterators as always present (TypeScript 5.6 and later) |
The dotted edge matters. strictPropertyInitialization only has an effect when strictNullChecks is also on. If you enable it alone, the compiler reports a configuration error.
What each flag looks like in code
Later chapters cover noImplicitAny and strictNullChecks in detail. Here is a short example of each flag so you can recognize the errors.
noImplicitAny and strictNullChecks
// Error: Parameter 'x' implicitly has an 'any' type.
function double(x) {
return x * 2;
}
// Error: 'text' is possibly 'null'.
function lengthOf(text: string | null): number {
return text.length;
}strictFunctionTypes
Without this flag, TypeScript allows a function that needs a Dog to stand in for one that receives any Animal. That is unsafe, because the caller may pass a cat.
type Animal = { name: string };
type Dog = Animal & { bark(): void };
let feed: (animal: Animal) => void = (a) => console.log(a.name);
const feedDog: (dog: Dog) => void = (d) => d.bark();
// Error: Type '(dog: Dog) => void' is not assignable to type '(animal: Animal) => void'.
feed = feedDog;The check applies to function-typed properties and parameters. Members declared with method syntax, such as bark(): void in an interface, are still compared loosely. This exception exists so that common patterns, like Array<T> being assignable to Array<U> for a subtype, keep working.
strictBindCallApply
Without the flag, call, apply, and bind accept anything. With it, they use the target function's real signature.
function add(a: number, b: number): number {
return a + b;
}
console.log(add.call(undefined, 1, 2));
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.
add.call(undefined, 1, "2");noImplicitThis
const counter = {
count: 0,
makeIncrementer() {
return function () {
// Error: 'this' implicitly has type 'any' because it does not have a type annotation.
this.count++;
};
},
};A regular function has its own this, which is not counter. An arrow function would capture the outer this and fix the error. You can also declare a this parameter, such as function (this: { count: number }) { ... }.
strictPropertyInitialization
class User {
name: string;
email?: string;
constructor(name: string) {
this.name = name;
}
}This class compiles. If you delete the this.name = name line, the compiler reports that name has no initializer and is not definitely assigned in the constructor. The optional email property is allowed to stay unset because its type includes undefined.
useUnknownInCatchVariables
JavaScript lets code throw anything, so the caught value is typed unknown. You must narrow it before use.
try {
JSON.parse("{");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}alwaysStrict
This flag differs from the others. It does not add type errors. It parses your files in JavaScript strict mode and writes "use strict" at the top of each emitted file. That turns silent mistakes, such as assigning to an undeclared variable, into runtime errors. ES modules are always strict already, so the flag mostly matters for CommonJS output.
Overriding individual flags
Setting "strict": true and then listing a single flag gives you the whole group with one exception. The explicit setting wins, regardless of order in the file.
{
"compilerOptions": {
"strict": true,
"strictPropertyInitialization": false
}
}This is the standard way to adopt strict mode in steps. It also lets a package turn a flag off when it extends a shared base file.
What strict does not include
Several useful checks are separate flags and stay off unless you enable them.
noUncheckedIndexedAccessaddsundefinedto the type of array and index-signature reads.noImplicitOverriderequires theoverridekeyword on methods that replace a base class method.exactOptionalPropertyTypesstops you from assigningundefinedto an optional property unless its type allows it.noImplicitReturnsreports functions where some code paths return a value and others do not.noFallthroughCasesInSwitchreportscaseblocks that run into the next one.noUnusedLocalsandnoUnusedParametersreport unused declarations.
A later chapter covers these in more detail.
Common mistakes
- Assuming
strictis frozen. A compiler upgrade can add a flag to the group. Read the release notes when you upgrade. - Enabling
strictPropertyInitializationalone. It requiresstrictNullChecks. - Disabling flags to silence errors permanently. Use an override as a temporary step, and keep a list of the flags you turned off.
- Believing strict makes code safe. Strict mode checks types at compile time. Data from
JSON.parse, network calls, andascasts is still unchecked at runtime. - Using
!oras anyto clear errors. A non-null assertion or a cast hides the problem, and the error comes back at runtime.
Exercise
Exercise
Your tsconfig.json contains "strict": true and "strictNullChecks": false. Which strict flag will now produce a configuration problem or lose its effect, and why? Also name one check that stays off even though "strict" is true.
Show answer
strictPropertyInitialization. It depends on strictNullChecks, so with strictNullChecks off it has no effect, and the compiler can report an error for the unsupported combination. A check that stays off is noUncheckedIndexedAccess (noImplicitOverride and exactOptionalPropertyTypes also qualify), because strict does not include it.