Understanding TypeScript Strict Mode

Summary

Why you should enable strict mode in your TypeScript projects

Content

Understanding TypeScript Strict Mode

TypeScript’s strict mode is a collection of type-checking options that enable the most rigorous type checking possible. In this post, we’ll explore why you should always use it.

What is Strict Mode?

Strict mode enables the following options:

  • noImplicitAny: Disallows variables with implicit any type
  • strictNullChecks: Includes null and undefined in type checking
  • strictFunctionTypes: Ensures function type parameters are contravariant
  • strictBindCallApply: Better type checking for bind, call, and apply
  • strictPropertyInitialization: Checks for class property initialization
  • noImplicitThis: Disallows implicit any type for this
  • alwaysStrict: Parses code in strict mode

Why Use Strict Mode?

1. Catch Bugs Early

// Without strict mode
function add(a, b) {
  return a + b; // Parameters have implicit any type
}

// With strict mode
function add(a: number, b: number): number {
  return a + b; // Types are explicit
}

2. Better Tooling

With strict mode, IDEs can provide:

  • More accurate autocomplete
  • Better error messages
  • Improved refactoring support

3. Self-Documenting Code

Types serve as documentation. Strict mode ensures your documentation is accurate.

How to Enable

Add to your tsconfig.json:

{
  "compilerOptions": {
    "strict": true
  }
}

Migration Strategy

If you’re adding strict mode to an existing project:

  1. Enable it incrementally
  2. Fix errors one at a time
  3. Use any sparingly as a temporary workaround
  4. Gradually improve type coverage

Conclusion

Strict mode might feel restrictive initially, but it prevents bugs and improves code quality. The short-term pain is worth the long-term benefits.

Start with strict mode enabled for new projects, and gradually migrate existing codebases. Your future self will thank you.