[英]How to prevent a member from being undefined within a constructor using TypeScript?
我通過編寫這樣的類引入了一個錯誤:
class SomeClass {
private readonly item: string;
constructor(item: string) {
// bug, item is never assigned
}
public getInfo(): string {
return this.item; // always returns `undefined`
}
}
該項目永遠不會被分配,因此每次調用getInfo()
都會返回undefined
。 但是,此代碼成功轉譯。
我當前項目的代碼風格通過 tslint 的no-parameter-properties
規則阻止使用簡寫構造函數,因此我不能這樣做:
class SomeClass {
public constructor(private readonly item: string) {
}
public getInfo() {
return this.item;
}
}
由於我的 tsconfig 的strictNullChecks
設置,我期望 tsc 拋出錯誤。
有沒有辦法讓打字稿檢測到這個錯誤並將其編譯標記為錯誤?
這是我當前的tsconfig.json
compilerOptions:
"compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"es2017",
"DOM"
],
"module": "commonjs",
"pretty": true,
"outDir": "dist",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
}
如果你有 tsc >=2.7.1,那么你要么在尋找編譯器選項
--strict
啟用所有嚴格的類型檢查選項。 啟用
--strict
啟用--noImplicitAny
、--noImplicitThis
、--alwaysStrict
、--strictNullChecks
、--strictFunctionTypes
和--strictPropertyInitialization
。
因為它包含所有嚴格的規則集。
或者更具體地說
--strictPropertyInitialization
因為那個是為您的用例設計的:
確保在構造函數中初始化非未定義的類屬性。 此選項需要啟用
--strictNullChecks
才能生效。
使用該設置,tsc 現在將拋出:
src/SomeClass.ts:2:22 - error TS2564: Property 'item' has no initializer and is not definitely assigned in the constructor.
2 private readonly item: string;
~~~~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.