Incorporating Typescript strict mode in large projects
Adopting TypeScript’s strict mode is one of the best ways to improve type safety and make our codebase more robust. But for large projects though, enabling strict mode all at once is not feasible. In this article, we will explore an incremental adoption solution for this problem: typescript-strict-plugin by Allegro Tech.
Let’s begin by installing it into our project:
npm i --save-dev typescript-strict-plugin
We can now opt for 2 different solutions, depending on the needs of the development team.
Excluding files by using comments
The originally intended way to use this package. First, we need to add the typescript-strict-plugin to our tsconfig.json:
{
"compilerOptions":{
...,
"strict":false,
"plugins":[
{
"name":"typescript-strict-plugin"
}
]
}
}
Then, we can just run the following script to automatically annotate all files with existing strict errors:
./node_modules/.bin/update-strict-comments
New tsconfig file
We recommend using this alternative solution if our team has any of the following objections regarding the adoption of strict mode:
- Comments are forbidden by linting software.
- We want to run the strict-checking step separatedly and at a specific point of our build pipeline.
- We prefer having which files have already been migrated specified in a separate file.
First, we need to create a new tsconfig.tscstrict.json file that extends our current tsconfig.json. In its “includes” array, we will add each file that we migrate.
Then, we can add a script that runs against our new tsconfig:
"check-ts-strict": "tsc-strict --project path/to/tsconfig.tscstrict.json"
We can now run this script at any step we need (e.g. in the pre-commit Git hook).
Related Posts
Post not found!