Typescript strictNullChecks with limited scope
If your dependencies are all in .js
and .d.ts
files (that is, not ts source) then you can use a flag and tell the compiler to skip checking your libs, which will result in no errors from the libs.
There are two new flags for that:
skipLibCheck
:
Don’t check the default library (
lib.d.ts
) file’s validity
skipDefaultLibCheck
:
Don’t check a user-defined default library (
*.d.ts
) file’s validity
And a bit more about it in the What's new in Typescript 2:
TypeScript 2.0 adds a new
--skipLibCheck
compiler option that causes type checking of declaration files (files with extension.d.ts
) to be skipped. When a program includes large declaration files, the compiler spends a lot of time type checking declarations that are already known to not contain errors, and compile times may be significantly shortened by skipping declaration file type checks.Since declarations in one file can affect type checking in other files, some errors may not be detected when
--skipLibCheck
is specified. For example, if a non-declaration file augments a type declared in a declaration file, errors may result that are only reported when the declaration file is checked. However, in practice such situations are rare.
If you'd like to scope strictNullChecks
to a particular directory within your project, you can do it with an extends
clause in your tsconfig.json
. For example, if your project looks like this:
a/
code.ts
b/
other.ts
tsconfig.json
And you want to enable strict null checking within a
, you could add a/tsconfig.json
:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"strictNullChecks": true
}
}
When you run tsc
from inside directory a
, you'll get strict null checks for a/code.ts
.
This approach isn't without drawbacks:
- If
a/code.ts
imports../b/other.ts
, then you'll get strict null checking forb/other.ts
, too. - If you run
tsc
from the root directory, you won't get strict null checking fora/code.ts
.
You're effectively creating a new, strict, sub-project within your larger project. You'd want to make sure to run tsc
for both projects as part of your build process. It's not perfect, but it might help you migrate a large project to strictNullChecks
bit by bit.
Is there a way to declare a directory / file / module / class as abiding by strictNullChecks, even when the overall project cannot be compiled with the flag
No.
Note: There is a feature request to ignore errors for certain files that hasn't come to fruitation : https://github.com/Microsoft/TypeScript/issues/11051