typescript - Hur man seninitierar icke-nullbara variabler?
I mina tester måste jag ofta deklarera en variabel högst upp, som jag kommer att använda i beforeAll och afterAll.
Exempel:
describe('My test suite', () => {
let app: Server;
beforeAll(async () => {
app = await Server.init();
});
afterAll(async () => {
await app.close();
});
});
Problemet är att när jag slår på strictNullChecks får jag en varning på raden let app: Server; "Tilldelar ett nullable värde till en icke-nullbar variabel".
Finns det en motsvarighet till nyckelordet late i Dart?
Självklart kan jag göra let app: Server | undefined; men då måste jag app!.close(). Jag undrar om det finns ett bättre sätt att göra detta.
Redigera
Här är den grundläggande 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",
]
}
Jag förlängde det för att använda det med ESLint:
// tsconfig.eslint.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strictNullChecks": true
}
}
Och sedan min 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'],
},
},
},
};
Svar #1
Du kan använda bang-tecknet för icke-null-försäkran före : som används för att deklarera en variabels typ för att tala om för TypeScript-systemet att du hanterar nullbarheten:
describe('My test suite', () => {
let app!: Server;
beforeAll(async () => {
app = await Server.init();
});
afterAll(async () => {
await app.close();
});
});
Svar #2
Mitt sätt att kringgå detta är att ignorera regeln i mina specifikationer.
.eslintrc.js{
...,
overrides: [
{
files: ['**spec.ts'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
rules: {
'strict-null-checks/all': 'off',
},
},
],
}
