Strict mode in TypeScript is a compiler option that enables a set of stricter type checking and safety features to help you write more robust, accurate, and maintainable code. It’s represented by the ‘–strict‘ flag in the ‘tsconfig.json‘ configuration file. When enabled, it activates several type checking and safety options, such as:
1. ‘noImplicitAny‘ - Disallows any implicit ‘any‘ types, forcing the programmer to provide type annotations.
2. ‘noImplicitThis‘ - Disallows using ‘this‘ in a function that’s not inside a class or object when the type is not known.
3. ‘alwaysStrict‘ - Enforces the use of ’use strict’ directive; parses ECMAScript modules in strict mode.
4. ‘strictNullChecks‘ - Disallows assigning ‘null‘ or ‘undefined‘ to non-nullable types.
5. ‘strictFunctionTypes‘ - Tightens the type checking for functions, ensuring that they are of compatible types.
6. ‘strictBindCallApply‘ - Ensures a more accurate type checking for ‘bind‘, ‘call‘, and ‘apply‘ methods.
7. ‘strictPropertyInitialization‘ - Ensures that class properties are initialized in the constructor, either directly or indirectly.
You can enable strict mode in the ‘tsconfig.json‘ file like this:
{
"compilerOptions": {
"strict": true
}
}
Here’s an example to further illustrate the difference strict mode can make:
class Sample {
name: string; // Without strict mode, this can be left uninitialized
constructor(name?: string) {
if (name) {
this.name = name;
}
}
printName() {
console.log(this.name.toUpperCase());
}
}
let instance = new Sample();
instance.printName(); // Throws a runtime error, since `name` is undefined
When strict mode is enabled, TypeScript will report an error on the ‘name‘ property because it’s not initialized. To fix this issue, you either need to provide a default value or declare it as a nullable type:
class Sample {
name: string = "default"; // Provide a default value, or declare it as `string | undefined`
constructor(name?: string) {
if (name) {
this.name = name;
}
}
printName() {
console.log(this.name.toUpperCase());
}
}
In conclusion, strict mode helps you catch potential issues in your code during the development and compilation stages, thus ensuring your code is more robust and maintainable.