What Is TypeScript Strict Mode and Why Should You Use It?

Learn What Is TypeScript Strict Mode and Why Should You Use It? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Strict Mode

TypeScript helps developers identify problems before JavaScript code runs. However, the number of problems it detects depends partly on the compiler settings used by a project.

Strict mode is a compiler configuration that enables a collection of stricter type-checking options. These checks help identify issues involving implicit any types, null and undefined values, function compatibility, uninitialized class properties, and other common sources of runtime errors.

You enable strict mode through the strict option in tsconfig.json. Rather than manually enabling every foundational strictness option, you can use one setting to activate the group together.

Strict mode is particularly valuable for new TypeScript projects because it encourages explicit contracts and safer handling of uncertain values. Existing projects can adopt it gradually by enabling individual checks, addressing the resulting errors, and eventually switching on the complete strict group.

1. Enabling Strict Mode in tsconfig.json

The easiest way to enable strict mode is to add strict: true to the compilerOptions section of your TypeScript configuration file.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true
  },
  "include": ["src/**/*.ts"]
}

With this configuration, TypeScript applies the strictness checks included in the strict option when checking the project.

Strict mode does not require you to write a type annotation for every variable. TypeScript continues to infer types from expressions, initial values, function returns, and surrounding context. The goal is to prevent unsafe assumptions where the compiler cannot establish an appropriate type.

If your project already has a tsconfig.json file, you can add the setting to its existing compilerOptions object. Avoid creating a second configuration or replacing your framework's existing settings unnecessarily.

To check the project without generating output, run the following command from the project directory:

npx tsc --noEmit

This command checks the TypeScript project using its configuration and reports diagnostics. If your framework uses a separate build system, use its supported type-checking workflow as well.

2. Understanding the Checks Enabled by Strict Mode

The strict option enables several individual compiler options that work together to improve type safety.

Compiler option Purpose
noImplicitAny Reports places where TypeScript would otherwise infer any implicitly.
strictNullChecks Requires null and undefined to be handled according to their types.
strictFunctionTypes Applies stricter compatibility checks to function parameter types in applicable contexts.
strictBindCallApply Checks arguments passed through bind, call, and apply more accurately.
strictPropertyInitialization Checks that declared class properties are initialized appropriately.
noImplicitThis Reports certain uses of this that would otherwise have an implicit any type.
alwaysStrict Parses files in strict mode and emits JavaScript with a strict-mode directive when applicable.
useUnknownInCatchVariables Uses unknown as the default type of catch clause variables.

These options cover different situations. Some affect how values are typed, while others check function compatibility, class initialization, or JavaScript output.

Strict mode does not enable every possible safety-related compiler option. For example, noUncheckedIndexedAccess and exactOptionalPropertyTypes remain separate options that you can enable independently.

3. noImplicitAny

The any type effectively disables many of TypeScript's checks for a value. When a value has type any, you can perform operations on it without the compiler requiring evidence that those operations are valid.

The noImplicitAny option reports cases where TypeScript would otherwise assign any implicitly. This encourages developers to provide useful type information or structure the code so the type can be inferred.

// With noImplicitAny enabled, this causes an error:
// function greet(name) {
//   return "Hello, " + name.toUpperCase();
// }

function greet(name: string): string {
  return "Hello, " + name.toUpperCase();
}

console.log(greet("Asha"));

In the first declaration, TypeScript cannot infer a parameter type from the function implementation alone, so it reports the implicit any parameter under strict checking.

The corrected function declares name as string, making the toUpperCase operation valid according to its parameter contract.

Explicitly writing any can still bypass type checking. noImplicitAny is not the same as banning every use of any, so prefer unknown or a more precise type when the actual value is uncertain.

4. strictNullChecks

JavaScript values can be missing, null, or undefined. When strictNullChecks is disabled, TypeScript permits many operations that assume these values are present, even when that assumption may be incorrect at runtime.

With strictNullChecks enabled, null and undefined are distinct types. Code must check for these possibilities or handle them through a suitable type design before using a value as though it were definitely present.

function getUserName(
  name: string | undefined
): string {
  if (name === undefined) {
    return "Guest";
  }

  return name.toUpperCase();
}

console.log(getUserName("Asha"));
console.log(getUserName(undefined));

The parameter explicitly allows a string or undefined. The function checks which value is present before calling toUpperCase.

This check prevents code from treating an absent value as a definite string. It also documents what the function should do when the value is unavailable.

The same principle applies to optional object properties, array lookups, functions that might not return a matching value, and API responses containing missing data.

5. strictPropertyInitialization

Class properties sometimes need a value before an instance is used. If a property is declared but never initialized, reading it can produce undefined even when its declared type suggests that it should contain a definite value.

The strictPropertyInitialization option checks that class properties are initialized through a property initializer or constructor assignment that TypeScript can recognize, or are explicitly designed to support values that may be unavailable.

class User {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  getLabel(): string {
    return "User: " + this.name;
  }
}

const user = new User("Asha");

console.log(user.getLabel());

The constructor assigns name before the instance is used, satisfying the initialization requirement.

If a property is optional, declare it with an appropriate optional type. If the property is populated later by a framework or dependency injection mechanism, ensure the initialization model is sound instead of using an assertion simply to silence an error.

Definite assignment assertions using an exclamation mark can tell TypeScript that a property will be initialized elsewhere. They do not initialize the property at runtime, so they should be used only when another mechanism genuinely guarantees that initialization.

6. strictFunctionTypes

Functions accept and produce values, so their parameter and return types influence whether one function can safely be used in place of another.

strictFunctionTypes checks function parameter compatibility more rigorously in applicable contexts. This helps catch cases where a function requires a narrower input than the caller is allowed to provide.

interface Animal {
  name: string;
}

interface Dog extends Animal {
  bark(): void;
}

type AnimalHandler = (animal: Animal) => void;

const handleDog = (dog: Dog): void => {
  dog.bark();
};

// With strictFunctionTypes enabled,
// this assignment is rejected:
// const handler: AnimalHandler = handleDog;

const handleAnimal: AnimalHandler = (animal) => {
  console.log(animal.name);
};

const dog: Dog = {
  name: "Max",
  bark() {
    console.log("Woof");
  }
};

handleAnimal(dog);

An AnimalHandler must be able to handle any Animal. A handler that requires a Dog is not safe for that contract because another caller might pass an Animal that does not have a bark method.

The reverse assignment is generally safe for this parameter relationship: a function that can handle any Animal can also handle a Dog.

TypeScript retains some compatibility exceptions, including method and constructor parameter bivariance in relevant contexts. Therefore, strictFunctionTypes should be understood as a stricter function compatibility rule rather than a guarantee that every possible callback assignment follows fully contravariant rules.

7. strictBindCallApply

JavaScript functions support call, apply, and bind, which allow a function to be invoked or prepared with a particular this value and arguments.

The strictBindCallApply option improves checking for these operations by verifying that the supplied arguments match the function's parameter types.

function add(a: number, b: number): number {
  return a + b;
}

console.log(add.call(undefined, 10, 20));
console.log(add.apply(undefined, [5, 7]));

const addFive = add.bind(undefined, 5);

console.log(addFive(10));

// Compile-time error:
// add.call(undefined, "10", 20);

// Compile-time error:
// add.apply(undefined, [5, "7"]);

The function requires two numeric arguments. The call and apply examples provide compatible values, and bind creates a new function with the first argument fixed to 5.

Strict checking helps catch incompatible arguments before those operations execute. Without appropriate checks, mistakes involving argument types can remain hidden until runtime.

8. noImplicitThis and alwaysStrict

Strict mode also includes checks that affect this and JavaScript strict-mode behavior.

noImplicitThis reports certain contexts where this would otherwise receive an implicit any type. It encourages developers to clarify the intended receiver type when TypeScript cannot infer it safely.

interface Counter {
  value: number;
  increment(): void;
}

const counter: Counter = {
  value: 0,

  increment() {
    this.value += 1;
  }
};

counter.increment();

console.log(counter.value);

In this example, contextual typing gives this the Counter type within the method, so TypeScript knows that this.value is a number.

When functions are detached from their original objects, or when callbacks use this in unusual ways, an explicit this parameter or a different function design may be necessary.

alwaysStrict causes TypeScript to parse files in strict mode and emit a strict-mode directive in generated JavaScript where applicable. JavaScript strict mode changes certain runtime language behaviors, such as how some invalid assignments are handled.

Do not confuse JavaScript's runtime strict mode with TypeScript's strict compiler option. TypeScript strict mode enables a group of type-checking settings, while alwaysStrict controls JavaScript strict-mode parsing and output.

9. useUnknownInCatchVariables

JavaScript allows code to throw different kinds of values, not just Error objects. An exception could be an Error, a string, a number, or even an object with an unexpected structure.

With useUnknownInCatchVariables enabled, which is part of strict mode, an unannotated catch variable has type unknown. You must narrow it before relying on properties or methods specific to a particular type.

try {
  throw new Error("Unable to load data");
} catch (error: unknown) {
  if (error instanceof Error) {
    console.log(error.message);
  } else {
    console.log("An unexpected error occurred");
  }
}

The instanceof check narrows error to Error in the first branch, where message is available. The other branch handles values that do not satisfy the check.

This makes error handling more robust because the code does not assume every thrown value has the same structure.

If your application expects errors with a custom structure, use a suitable type guard or validation function to verify that structure before accessing its properties.

10. Strict Mode and Type Inference

Enabling strict mode does not mean every variable needs a manual type annotation. TypeScript can infer many types from initialization values and the surrounding code.

const name = "Asha";
const score = 95;
const active = true;

const scores = [85, 90, 95];

function calculateTotal(a: number, b: number) {
  return a + b;
}

console.log(name.toUpperCase());
console.log(score.toFixed(2));
console.log(active);
console.log(scores.length);
console.log(calculateTotal(10, 20));

TypeScript infers useful types for the constants, the array, and the return value of calculateTotal. Explicit annotations are most useful when they clarify a public contract, resolve ambiguity, or describe a range of valid values that cannot be inferred directly.

Function parameters often need more attention because their intended types usually cannot be determined from the function body alone. Strict mode helps identify parameters that lack adequate type information.

A good strict-mode codebase balances explicit contracts with inference. Avoid adding redundant annotations to every local variable simply because strict mode is enabled.

11. Strict Mode Does Not Enable Every Safety Check

Strict mode strengthens TypeScript's type checking, but it does not activate every option available for detecting potentially unsafe code.

For example, noUncheckedIndexedAccess and exactOptionalPropertyTypes are separate settings. They can provide additional checks for dynamic property lookups and optional properties.

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true
  }
}

With noUncheckedIndexedAccess enabled, a dictionary lookup may produce a value that includes undefined. Code must verify that the entry exists before treating it as a definite value.

With exactOptionalPropertyTypes enabled, a property declared as name?: string may be absent, but explicitly assigning undefined is not allowed unless undefined is included in the property type.

These options can make type models more precise, but they may also produce new errors in existing code. Enable them based on the project's requirements and review their effects before introducing them into a large application.

12. Migrating an Existing Project to Strict Mode

Enabling strict mode in a mature codebase can reveal many errors at once, especially if the project was originally developed with weaker type checking.

A gradual migration allows you to improve type safety without requiring every existing file to be fixed in one large change.

Step 1: Record the current state

Run the existing type-checking or build command and identify the compiler configuration currently used by the project. Keep a reference to the baseline errors and build behavior.

Step 2: Enable individual checks

Where appropriate, enable checks such as noImplicitAny and strictNullChecks individually. Fix errors by adding accurate types, narrowing uncertain values, and handling missing data properly.

Step 3: Improve shared contracts

Update commonly used interfaces, API response models, callback signatures, and class constructors. Improving shared types can resolve multiple related errors at once.

Step 4: Enable strict mode

Once the codebase is ready, enable strict: true and resolve the remaining issues. You can retain explicit overrides for selected strictness flags temporarily, but track them as migration work rather than leaving unclear exceptions indefinitely.

Step 5: Verify the whole build

Run type checking, tests, and the production build. Confirm that application behavior and third-party integrations remain correct after changing the compiler settings.

If the project uses a framework-specific compiler, inspect its supported configuration and build commands. An Angular or other framework application may perform compilation through tooling that has its own additional checks.

13. Common Strict Mode Errors and How to Fix Them

Parameter implicitly has an any type

Add an appropriate parameter type or restructure the function so TypeScript can infer the parameter type from its context. Avoid adding any merely to silence the diagnostic.

Object is possibly undefined

Check that the value exists before accessing its properties. Use conditional checks, optional chaining, nullish coalescing, or an explicit fallback according to the intended behavior.

Property has no initializer

Initialize the property at declaration or in the constructor. If it can genuinely be absent, model that possibility in the type. Use definite assignment assertions only when initialization is guaranteed by another mechanism.

Callback types are incompatible

Check whether the callback can safely accept every input that the caller may provide. Narrow parameter types can make a callback incompatible with a broader contract.

Catch variable is unknown

Narrow the caught value with instanceof, typeof, or an appropriate custom type guard before using its properties. Thrown values are not guaranteed to be Error objects.

Temptation to disable strict mode

Review the diagnostic to understand whether the problem is a missing type, an unsafe assumption, or an incorrect contract. Fix the underlying issue where possible rather than removing useful checks across the project.

Best Practices for Strict Mode

  • Enable strict mode for new TypeScript projects unless a specific compatibility requirement prevents it.
  • Use accurate types and control-flow narrowing instead of relying on any or unchecked type assertions.
  • Model null and undefined explicitly when a value can be absent.
  • Initialize class properties before they are used and make later initialization guarantees clear.
  • Design callbacks to accept all input types permitted by their calling contracts.
  • Use unknown when receiving values whose actual types are not yet known, including caught exceptions.
  • Keep strict mode enabled while migrating a codebase and track any temporary compiler-option overrides.
  • Consider noUncheckedIndexedAccess and exactOptionalPropertyTypes for further protection around missing values.
  • Do not confuse static type checking with runtime validation of API responses or user input.
  • Run the application's tests and production build after configuration changes.
  • Inspect framework-specific type-checking behavior when the compiler is integrated into a framework build system.
  • Review compiler diagnostics after TypeScript upgrades because stricter or improved checks can reveal additional issues.

Conclusion

Strict mode is one of the most useful TypeScript configuration settings because it enables a group of checks that catch common programming mistakes before runtime. These checks improve the handling of uncertain values, function compatibility, class initialization, and type inference.

The most important habit is to treat compiler errors as information about your application's contracts. Adding accurate types, narrowing uncertain values, and correcting incompatible function signatures usually results in code that is easier to understand and maintain.

For new projects, enable strict mode early. For established projects, introduce its checks gradually, fix errors systematically, and verify the complete build. As your codebase grows, strong compiler settings help make future changes safer and more predictable.

Code Examples

Enabling Strict Mode

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "strict": true
  },
  "include": ["src/**/*.ts"]
}
    

The strict option enables a collection of strict type-checking options. TypeScript continues to infer types where possible but reports unsafe or insufficiently typed constructs covered by these checks.

Fixing an Implicit Any Error

typescript
// With noImplicitAny enabled, this is an error:
// function greet(name) {
//   return "Hello, " + name.toUpperCase();
// }

function greet(name: string): string {
  return "Hello, " + name.toUpperCase();
}

console.log(greet("Asha"));
    

Declaring the parameter as string gives TypeScript the information needed to check its operations and prevents an implicitly inferred any parameter.

Handling Null and Undefined

typescript
function getUserName(
  name: string | undefined
): string {
  if (name === undefined) {
    return "Guest";
  }

  return name.toUpperCase();
}

console.log(getUserName("Asha"));
console.log(getUserName(undefined));
    

strictNullChecks requires the function to account for undefined before treating the parameter as a definite string.

Initializing Class Properties

typescript
class User {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  getLabel(): string {
    return "User: " + this.name;
  }
}

const user = new User("Asha");

console.log(user.getLabel());
    

strictPropertyInitialization checks that required class properties are initialized through a recognized property initializer or constructor path.

Safely Handling Unknown Errors

typescript
try {
  throw new Error("Unable to load data");
} catch (error: unknown) {
  if (error instanceof Error) {
    console.log(error.message);
  } else {
    console.log("An unexpected error occurred");
  }
}
    

The catch variable is unknown until narrowed. Checking instanceof Error makes its message property available in the appropriate branch.

Additional Strictness Options

json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true
  }
}
    

These additional options strengthen checks for missing indexed values and optional properties. They are configured separately from strict and can expose new diagnostics in existing code.

Pro Tip

Enable strict: true in new TypeScript projects and treat resulting errors as opportunities to improve type contracts. Use explicit types for public interfaces, narrow null and unknown values before accessing them, and initialize class properties correctly. Remember that noUncheckedIndexedAccess and exactOptionalPropertyTypes are separate options, and strict mode does not replace runtime validation of external data.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.