'How to late init non-nullable variables?
In my tests, I often have to declare a variable at the top, which I will use in the beforeAll and the afterAll.
Example:
describe('My test suite', () => {
let app: Server;
beforeAll(async () => {
app = await Server.init();
});
afterAll(async () => {
await app.close();
});
});
The problem is that when I turn on strictNullChecks, I get a warning on the line let app: Server; "Assigning nullable value to non-nullable variable".
Is there an equivalent to the late keyword in dart?
Of course, I can do let app: Server | undefined; but then I have to app!.close(). I'm wondering if there is a better way to do this.
Edit
Here is the base tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"allowSyntheticDefaultImports": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"esModuleInterop": true,
},
"exclude": [
"node_modules",
"dist",
]
}
I extended it to use it with ESLint:
// tsconfig.eslint.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strictNullChecks": true
}
}
And then my eslintrc.js:
module.exports = {
env: {
es6: true,
node: true,
},
extends: ['airbnb-base'],
ignorePatterns: ['.eslintrc.js'],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
project: './tsconfig.eslint.json',
},
plugins: [
'@typescript-eslint',
'strict-null-checks',
],
rules: {
'strict-null-checks/all': 'warn',
// Turn off no-shadow because of enum
// See: https://github.com/typescript-eslint/typescript-eslint/issues/325
'no-shadow': 'off',
'no-dupe-class-members': 'off',
'@typescript-eslint/no-dupe-class-members': ['error'],
'@typescript-eslint/explicit-function-return-type': ['warn', {
allowExpressions: true,
}]
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
},
};
Solution 1:[1]
You can use the bang non-null assertion character before the : used to declare the type of a variable to tell the TypeScript system that you are handling the nullability:
describe('My test suite', () => {
let app!: Server;
beforeAll(async () => {
app = await Server.init();
});
afterAll(async () => {
await app.close();
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sno2 |
