'Best way to handle uninitialised class values in TypeScript - Object is possibly 'null'
I've created a wrapper class for S3 operations but when I compile using the TypeScript complier I get the following error:
lib/Store.ts:20:15 - error TS2531: Object is possibly 'null'.
20 await this.store.upload({
I'm new to TypeScript but I understand TypeScript is doing it's job here and preventing the possibility that await this.store.upload() could run while this.store is null. What's the correct way for dealing with this type of situation where a class value might not yet be initialised?
My wrapper class:
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();
}
}
I've always tried to avoid creating new instances of classes in the constructor because it's awkward to mock. Maybe passing a new class instance into the constructor is the best approach?
Solution 1:[1]
You can try
{
...
"strictNullChecks": true,
"strictPropertyInitialization": true,
...
}
"strictNullChecks" tells the compiler to watch for any declared variables that evaluate to null or undefined and raise on error on at compiler time (https://www.typescriptlang.org/tsconfig#strictNullChecks) "strictPropertyInitialization" tells the compiler to raise an error 'when a class property was declared but not set in the constructor'. (https://www.typescriptlang.org/tsconfig#strictPropertyInitialization)
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 | Dharman |
