Skip to content
jshacks.dev
TypeScript

Strict Mode in TypeScript: What Each Flag Does

TypeScript strict mode is a bundle of separate flags. See what noImplicitAny, strictNullChecks and the rest catch, with the exact compiler errors.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js and JavaScript logos.

"strict": true in a tsconfig.json looks like one switch, but it is a bundle. Turning it on enables a family of flags, each of which closes a specific gap in the type system, and each reports its own errors. Knowing which flag produces which error makes strict mode much less mysterious, and it lets you adopt it in an existing project one flag at a time. This post goes through the flags in the family, shows the exact message each one produces, and then covers a few useful options that strict does not include. It targets TypeScript 6.x, and the authoritative list is in the tsconfig reference for strict.

What strict actually does

The strict option is a shortcut. Setting it to true turns on every flag in the strict family, and you can still switch an individual flag off by naming it with false. That makes the migration path simple: enable strict, then disable the flags that produce too many errors, and re-enable them one at a time.

tsconfig.jsonJSON
{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "strict": true,
    "strictPropertyInitialization": false
  }
}
Text
(no output: configuration is read by tsc on the next run)

The family includes noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, useUnknownInCatchVariables and alwaysStrict, plus newer additions such as strictBuiltinIteratorReturn. New releases can add flags to the family, which is one reason to pin your TypeScript version and read the release notes when upgrading.

noImplicitAny

Without this flag, a parameter with no annotation silently becomes any, which switches off checking for everything that touches it. With the flag, the compiler asks you to say what you mean.

implicit.tsTypeScript
function double(x) {
  return x * 2;
}
Text
implicit.ts(1,17): error TS7006: Parameter 'x' implicitly has an 'any' type.

The fix is function double(x: number): number. This is the flag that does the most for everyday safety, since any spreads: a value of type any passed into other code makes their results any too. If you are migrating a JavaScript project, expect this flag to produce the biggest list of errors.

The flag only complains where the type would be implicitly any. A callback whose type is known from context needs no annotation, because the compiler infers it from the receiving function.

strictNullChecks

Without this flag, null and undefined belong to every type, so string quietly means "string or nothing". With it, they are separate types, and you must handle them.

nulls.tsTypeScript
function length(s: string | null): number {
  return s.length;
}
Text
nulls.ts(2,10): error TS18047: 's' is possibly 'null'.

You fix it by narrowing before the access.

nulls-fixed.tsTypeScript
function length(s: string | null): number {
  if (s === null) {
    return 0;
  }
  return s.length;
}

console.log(length("abc"), length(null));
Text
3 0

This flag removes a whole category of runtime TypeError crashes, and it is the reason strict mode is worth the effort. It also means optional properties and array lookups can produce undefined in their types, and the compiler keeps track of it.

strictFunctionTypes

This flag controls how function parameters are compared when you assign one function type to another. With it on, parameters are checked contravariantly: a function that accepts less than the target promises is rejected.

functions.tsTypeScript
type Handler = (event: string) => void;

const onClick: Handler = (event: "click") => {
  console.log(event);
};
Text
functions.ts(3,7): error TS2322: Type '(event: "click") => void' is not assignable to type 'Handler'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'string' is not assignable to type '"click"'.

A Handler must accept any string, but the function written here only accepts the literal "click". Callers using the Handler type could pass "keydown", and the function would receive a value it never expected. The check applies to function-typed properties and function types. Methods declared with method syntax are deliberately left bivariant, for compatibility with common patterns such as event emitters and array methods.

strictBindCallApply

JavaScript's bind, call and apply take arguments loosely. With this flag, the compiler checks those arguments against the function being invoked.

bind.tsTypeScript
function greet(name: string): string {
  return `Hi ${name}`;
}

greet.call(undefined, 42);
Text
bind.ts(5,23): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

Without the flag, call would accept anything, because its parameters are typed as any. With it, the argument list is checked just like a normal call. This flag matters less in modern code that avoids bind, but it is cheap to keep on.

strictPropertyInitialization

A class property that is declared with a non-optional type must be given a value, or the compiler cannot promise that it is ever set.

init.tsTypeScript
class User {
  name: string;
}
Text
init.ts(2,3): error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.

You can initialize it where it is declared, assign it in the constructor, or make the type string | undefined. When a framework sets the value after construction, the definite assignment assertion name!: string tells the compiler you accept responsibility. Use that sparingly, because it is a promise the compiler does not check. The flag requires strictNullChecks to be on as well, since the idea of an unset property only matters when undefined is its own type.

noImplicitThis

Inside a function, this depends on how the function is called. If the compiler cannot work out its type, this becomes any without this flag, and an error with it.

this.tsTypeScript
function show() {
  return this.id;
}
Text
this.ts(2,10): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

The fix is to declare a this parameter, which exists only for the compiler and is erased from the output.

this-fixed.tsTypeScript
function show(this: { id: number }): number {
  return this.id;
}

console.log(show.call({ id: 7 }));
Text
7

With strictBindCallApply also on, the call here is checked against the declared this type, so the two flags work together.

useUnknownInCatchVariables

In JavaScript anything can be thrown, so the value caught in a catch clause is not necessarily an Error. With this flag, the variable is typed unknown instead of any.

catch.tsTypeScript
try {
  JSON.parse("{");
} catch (e) {
  console.log(e.message);
}
Text
catch.ts(4,15): error TS18046: 'e' is of type 'unknown'.

You handle it with a check.

catch-fixed.tsTypeScript
try {
  JSON.parse("{");
} catch (e) {
  if (e instanceof Error) {
    console.log("failed:", e.name);
  } else {
    console.log("failed with a non-error value");
  }
}
Text
failed: SyntaxError

The extra lines are the point: code that handled e.message for a thrown string would have printed undefined before, and now the compiler asks you to decide what to do.

alwaysStrict

The last flag in the family has no errors of its own. It emits "use strict" at the top of each generated file and parses your source in strict mode. ES modules are always strict, so in a modern project the flag has little visible effect. It matters for scripts that are not modules, where it turns silent mistakes such as assigning to an undeclared variable into errors.

Flags that strict does not include

Several valuable options are outside the family, and you opt into them separately. noUncheckedIndexedAccess adds undefined to the result of an index lookup.

index.tsTypeScript
const list: number[] = [1, 2, 3];
const first = list[0];
first.toFixed(1);
Text
index.ts(3,1): error TS18048: 'first' is possibly 'undefined'.

That error appears only with noUncheckedIndexedAccess on. Without it, list[0] is a plain number, even though an empty array would give undefined at runtime. Other options worth knowing are exactOptionalPropertyTypes, noImplicitOverride, noImplicitReturns and noFallthroughCasesInSwitch. They are stricter than strict, and teams add them once the base flags are comfortable.

Adopting it in an existing project

Do not try to fix everything at once. Enable strict, then list the flags that report the most errors, and switch those off in the config. Fix the flags with few errors first. strictBindCallApply, useUnknownInCatchVariables and noImplicitThis are usually quick. Then take strictNullChecks and noImplicitAny, which need real design work, one folder at a time if you use project references. Each time a flag is cleared, remove its false line, so the config moves steadily toward plain "strict": true.

Treat the error list as a to-do list with a clear purpose. Each message names a place where the compiler could not vouch for your code. Cleaning them up pays for itself the first time the compiler catches a missing null check before a user does.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.