在我的测试中,我经常必须在顶部声明一个变量,我将在
beforeAll
和
afterAll
.
例子:
describe('My test suite', () => {
let app: Server;
beforeAll(async () => {
app = await Server.init();
});
afterAll(async () => {
await app.close();
});
});
问题是当我打开
strictNullChecks
,我接到警告
let app: Server;
“为不可为null的变量分配可为null值”。
有等效的吗
late
dart中的关键字?
当然,我可以
let app: Server | undefined;
但是我必须
app!.close()
。我想知道是否有更好的方法。
编辑
这是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",
]
}
我将其扩展为与ESLint一起使用:
// tsconfig.eslint.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strictNullChecks": true
}
}
然后是我的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'],
},
},
},
};