我為 S3 操作創建了一個包裝類,但是當我使用 TypeScript 編譯器進行編譯時,我收到以下錯誤:
lib/Store.ts:20:15 - error TS2531: Object is possibly 'null'.
20 await this.store.upload({
我是 TypeScript 的新手,但我知道 TypeScript 在這里完成了它的作業,并防止了await this.store.upload()while this.storeis運行的可能性null。處理類值可能尚未初始化的這種情況的正確方法是什么?
我的包裝類:
import S3 from 'aws-sdk/clients/s3';
export class Store {
storeName: string;
store: S3 | null;
initialised: boolean;
constructor(storeName: string) {
this.storeName = storeName;
this.store = null;
this.initialised = false;
}
_init(): void {
this.store = new S3();
}
async _writeToStore(data: object, path: string): Promise<void> {
if (!this.initialised) this._init();
await this.store.upload({
Bucket: this.storeName,
Key: path,
Body: data
}).promise();
}
}
我一直試圖避免在建構式中創建新的類實體,因為模擬起來很尷尬。也許將一個新的類實體傳遞給建構式是最好的方法?
uj5u.com熱心網友回復:
Typescript 給你這個錯誤是因為你已經strictNullChecks啟用并且你的屬性store有null一個可能的型別。
您可以執行以下任何選項
選項 1 - 洗掉null型別
您可能可以將null型別放在 上store,因為您在建構式上設定該屬性的值,而您的代碼中沒有任何內容將其設定為null:
store: S3;
選項 2 - 添加非空斷言運算子
或者,如果this.store執行時永遠不會為空this.store.upload({...}),則可以添加一個非空斷言運算子(!),如下所示:
this.store!.upload({...})
這將告訴 Typescript 停止給出錯誤。請注意,這不會改變代碼的運行時行為,因此僅!在您知道該值不能是nullor時才使用它很重要undefined。
選項 3 -在之前store檢查值null
this.store您可以在呼叫之前顯式檢查null 值this.store.upload()。但是這個呼叫必須在同一個方法中完成,像這樣:
if (!this.store) {
this.store = new S3();
}
await this.store.upload({...});
這不起作用:
if (!this.store) {
this._init();
}
await this.store.upload({...});
結論
就個人而言,我會選擇選項 1。我假設您撰寫包裝器的原因S3是讓您的消費者不必實體化并直接使用S3物件,而是實體化并使用包裝器類/物件。
uj5u.com熱心網友回復:
你可以試試
{
...
"strictNullChecks": true,
"strictPropertyInitialization": true,
...
}
“ strictNullChecks ”告訴編譯器觀察任何宣告的變數,這些變數的計算結果為 null 或 undefined 并在編譯器時引發錯誤(https://www.typescriptlang.org/tsconfig#strictNullChecks)“ strictPropertyInitialization ”告訴編譯器引發一個錯誤'當一個類屬性被宣告但未在建構式中設定'。(https://www.typescriptlang.org/tsconfig#strictPropertyInitialization)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/434231.html
標籤:javascript 节点.js 打字稿 亚马逊-s3 tsc
下一篇:如何僅在我的網站中提供S3物件
