0
0
Typescriptprogramming~5 mins

TypeScript Strict Mode and Why It Matters

Choose your learning style9 modes available
Introduction

Strict mode helps catch mistakes early by making TypeScript check your code more carefully. It makes your programs safer and easier to fix.

When you want to avoid bugs caused by unexpected values.
When working on bigger projects with many files and people.
When you want clearer and more reliable code.
When learning TypeScript and wanting to understand types better.
When you want your code editor to help you find errors before running the program.
Syntax
Typescript
{
  "compilerOptions": {
    "strict": true
  }
}

Setting strict to true turns on many helpful checks at once.

You can also enable strict checks one by one if you want more control.

Examples
This turns on all strict checks for your TypeScript project.
Typescript
// Strict mode enabled in tsconfig.json
{
  "compilerOptions": {
    "strict": true
  }
}
Strict mode prevents assigning null to a string unless you allow it explicitly.
Typescript
// Example of strict null checks catching errors
let name: string = null; // Error in strict mode
Strict mode helps catch type mistakes like assigning a string to a number variable.
Typescript
// Without strict mode, this might not cause an error
let age;
age = 25;
age = 'twenty-five'; // No error without strict mode
Sample Program

This program greets a person by name. Strict mode prevents passing null by mistake.

Typescript
function greet(name: string) {
  console.log(`Hello, ${name.toUpperCase()}!`);
}

greet('Alice');
// greet(null); // Uncommenting this line causes error in strict mode
OutputSuccess
Important Notes

Strict mode helps you find problems before running your code.

It may feel strict at first, but it makes your code more reliable.

You can gradually enable strict mode in existing projects.

Summary

Strict mode makes TypeScript check your code more carefully.

It helps catch bugs early and improves code quality.

Enable it by setting "strict": true in tsconfig.json.