The Strict compiler option enforces the strict type checking in TypeScript by enabling all the strict type rules under the strict family. The helps us to enable strict type checking without having to enable each compiler option separately. Note that future Typescript versions may introduce additional stricter checking options & enable them by default under this flag.
Enabling the Strict Compiler Option
You can enable the strict options in tsconfig.ts
as shown below.
1 2 3 4 5 6 7 | { "compilerOptions": { "strict": true, /* Enable all strict type-checking options. */ } } |
Enabling the strict option enables the following compiler rules (known as strict mode family options).
- alwaysStrict
- strictBindCallApply
- strictFunctionTypes
- strictNullChecks
- strictPropertyInitialization
- useUnknownInCatchVariables
- noImplicitAny
- noImplicitThis
The Future TypeScript versions may add additional type checking options to the above list. Hence they are automatically enabled by default. This is a good thing, but beware it may also break your code.
Opting Out of Certain Options
You may want to opt out of some of the above compiler rules. In that case, you can disable them by adding those flags in the tsconfig file
For Example, the following tsconfig option enables all the stricter options except noImplicitThis
.
1 2 3 4 5 6 7 8 9 | { "compilerOptions": { "strict": true, /* Enable all strict type-checking options. */ "noImplicitThis":false /* Enable error reporting when `this` is given the type `any`. */ } } |
You can also use the ts-ignore
to ignore the error for a specific line of code.
For Example, the following throws Parameter ‘n’ implicitly has an ‘any’ type (noImplicitAny
) error.
1 2 3 4 5 6 | function fn(n) { //dosomething return true; } |
Adding the // @ts-ignore
above the line where the error is thrown will stop the TypeScript compiler from throwing the error.
1 2 3 4 5 6 7 | // @ts-ignore function fn(n) { //dosomething return true; } |