How to disable strictNullChecks in spec test files in Angular?

Viewed 8172

In my tsconfig.json I have rule "strictNullChecks": true but I don't want this in my tests which is all *.spec.ts files. So I was trying to override this flag in my tsconfig.spec.json but it doesn't work. What am I doing wrong?

tsconfig.json

{
    "compileOnSave": false,
    "compilerOptions": {
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noFallthroughCasesInSwitch": true,
        "strictNullChecks": true,
        "downlevelIteration": true,
        "importHelpers": true,
        "module": "esnext",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "alwaysStrict": true,
        "skipLibCheck": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2017",
            "dom"
        ],
        "baseUrl": "./ClientApp",
    },
    "angularCompilerOptions": {
        "strictTemplates": true,
        "strictOutputEventTypes": false
    }
}

tsconfig.spec.json

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/spec",
        "baseUrl": "./",
        "target": "es5",
        "types": [
            "jasmine",
            "node"
        ],
        "strictNullChecks": false
    },
    "files": [
        "test.ts",
        "polyfills.ts"
    ],
    "include": [
        "**/*.spec.ts",
        "**/*.d.ts"
    ]
}
1 Answers

Both VS Code and WebStorm look for the nearest to the opened file tsconfig.json for a configuration to be used for IDE TS support. They do not know about Angular's specific files such as tsconfig.app.json and tsconfig.spec.json. So the bad news is that it seems impossible to have support for different sets of preferences only depending on the file extension. The separation can be done only on folders level what means you need to put all the tests in one folder and the app code into another one.

The good news is that using angular-cli everything should compile correctly.

As a workaround, it is possible to use assertions

const y: string = null as any;

Or a bit safer way that allows tracking error after changing signatures shows error:

function f(dep: string) () { }
const x = f(null as any); // Ok

// And it won't notify you after changing the type of function argument
// what can be desirable in some cases
function f(dep: number) () { } 
const x = f(null as any as number); // Ok and will show error for incorrect type

Related