Looking to incorporate 2 classes for business logic within my application. Below is some pseudo code showcasing the use of object
and string
types to specify each logic:
Includes interface and class declarations;
interface IResult<T, E> {
result: T;
err: E;
}
class Fail<E> implements IResult<null, E> {
private readonly _error: E;
constructor(error: E) {
this._error = error;
}
get err(): E {
return this._error;
}
get result(): null {
return null;
}
}
class Success<T> implements IResult<T, null> {
private readonly _result: T;
constructor(result: T) {
this._result = result;
}
get err() {
return null;
}
get result(): T {
return this._result;
}
}
In need to acquire one of these instances from a service, for instance DetailsFactory
. The response type has been specified where Success
should give back object
and Fail
should provide string
:
type Result<T, E> = Success<T> | Fail<E>;
Furthermore, an interface is utilized:
interface IDetailsFactory {
make(): Result<object, string>;
}
class DetailsFactory implements IDetailsFactory {
private readonly _type: string;
private _operation: object;
constructor(type: string) {
this._type = type;
}
public make() {
switch (this._type) {
case '1': this._operation = {type: '1', name: 'First'}; break;
case '2': this._operation = {type: '2', name: 'Second'}; break;
case '3': this._operation = {type: '3', name: 'Third'}; break;
default: return new Fail('Type is not specified');
}
return new Success(this._operation);
}
}
Used like so:
const detailsFactory = new DetailsFactory('1');
const {result, err} = detailsFactory.make();
Upon receiving the expected object in the result
field, and null
in err
, running a check:
if (!err) {
console.log(result.name);
}
An issue arises with TypeScript showing the error
Error:(96, 14) TS2531: Object is possibly 'null'.
. While I can check result
instead of !err
, it's not as elegant and I prefer early function exit.
The question remains: how can I inform TypeScript that if there are no errors (!err = true)
, trust me to access data from the result
field without assuming result
is potentially null
when error = null
?