Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Incremental Strictness

Tags:

typescript

I have a fairly large Typescript project and I'd like to make it more strict. In particular, we have an issue with null-checking in a lot of places so I'd like to use the strict null-checks option. However, there are thousands of errors and its not exactly possible to fix that anytime soon.

But as I'm writing new code, I'd like to be strict with non-nullable types so I'm not piling onto the mess. Is there any way to incrementally improve the strictness of a Typescript project so all new code has strict null checks?

like image 288
Chet Avatar asked Aug 24 '17 23:08

Chet


People also ask

Should I use TypeScript strict mode?

If you just start a new project I highly recommend using strict mode in TypeScript. It will help you to avoid errors, typos, and mistakes in your code in the future. Strict mode constricts you in ways of writing your code. On other hand, you won't choose the way that will bring you to make a mistake.

Is TypeScript strict by default?

By default, TypeScript doesn't enable the strict mode: { "compilerOptions": { "target": "es5", ... }, ... } Also setting the value to false will fail: { "compilerOptions": { "strict": false, ... }, ... }

How do I turn off TypeScript strict mode?

Disable strict checks entirely by setting strictTemplates: false in the application's TypeScript configuration file, tsconfig.


2 Answers

You can use typescript-strict-plugin which allows you to turn on strict mode in specific files or directories.

1. Install the package

npm i -D typescript-strict-plugin

2. Add the plugin to your tsconfig.json

{
  "compilerOptions": {
    //...
    "strict": false,
    "plugins": [
      {
        "name": "typescript-strict-plugin",
      }
    ]
  }
}

3. Mark files you want to strictify with @ts-strict comment

Before:

//no strict comment here
...
const name: string = null; // no error here

After:

//@ts-strict
...
const name: string = null; // TS2322: Type 'null' is not assignable to type 'string'.
like image 180
Kamil Krysiak Avatar answered Oct 04 '22 20:10

Kamil Krysiak


I think that the optimal solution is to extend the tsconfig.json with a new one which enables strictNullChecks and which will be used in the IDE.

  1. When creating a new functionality there will be strictNullChecks errors in the IDE, it's OK.
  2. When refactoring existing code, the appeared strictNullChecks errors will cause you to fix the code. Thus, there will be a gradual migration of the source code to fully enable the strictNullChecks.
like image 39
wrager Avatar answered Oct 04 '22 21:10

wrager