Strict mode and linting
Chapter 4: TypeScript Architecture
Chapters - Table of contents
Now that all our data types are strong and external dependencies and legacy code are typed, let's focus on improving the existing types by updating the TypeScript compiler configuration and adding some ESLint TypeScript rules.

Strict mode

TypeScript's compiler comes with a "strict mode" that enable better type inference by apply stricter rules such as:
  • strictNullChecks: null and undefined are no longer included in all types, they should be listed explicitly
  • noImplicitAny: Any type inference leading to any will no longer be silent but raise an error
Enabling the TypeScript's compiler "strict mode" can be achieved by adding the following to your tsconfig.json: "strict": true.
Other compiler are worth enabling, such as:
  • allowUnreachableCode: false: prevent any unreachable code
  • noFallthroughCasesInSwitch: Ensures that any non-empty case inside a switch statement includes either break or return
Should I just enable all those options at once?
If you are working on a legacy project, certainly not!
Enabling strict mode (which regroup a set of other options) on a legacy project can results in hundreds of TypeScript errors.
The best approach is to enable the rules in the following order and incorporate the changes in the code gradually:
  1. disable allowUnreachableCode
  2. enable noFallthroughCasesInSwitch
  3. enable strictNullChecks
  4. enable noImplicitAny
  5. Finally, set strict: true

How to deal with errors?

Some TypeScript errors might take time to solve, sometimes too much time to solve given the raised issue.
Here are some temporary solutions that are safer than assigning a any type:
  • using the as operator to force type coercion to another type:
    myvar as unknown as MyType
  • use // @ts-expect-error comment to temporarily disable TypeScript for a line:
    Using this comment is more explicit about the nature of the temporary fix than using any.
  • for errors on accession "null or undefined values", use Optional chaining operator: ?.

The essential ESLint rules

The final step to any robust TypeScript project is to set the proper ESLint TypeScript rules.
Four rules are especially efficient at improving the stability of a codebase:

Conclusion

__
Enabling all the compiler options and ESLint rules above will educate the people working on the project to be more rigorous, which will result in more explicit and safer types.
We use cookies to collect statistics through Google Analytics.
Do not track
 
Allow cookies