I recently made this class to treat error as a value in typescript, i want to do in a way that you could chain methods that expects and returns Response
return-pattern.ts
:
// import { APIErrors } from "../errors/api-errors";
type SuccessResponse<T> = [null, T];
type Err = {message: string, stack: string, name: string}
type ErrResponse = [Err, null];
export type HandleResponse<T> = SuccessResponse<T> | ErrResponse;
export class Response<T> {
private _data: T | null
private _err: Err | null
private constructor (data:T | null ,err: Err | null) {
this._data = data
this._err = err
}
static success<T>(data: T): Response<T> {
return new Response(data, null)
}
static err<T>(err: Err): Response<T> {
return new Response(null, err) as Response<T>
}
bind<R>(func: (res: Response<T>) => Response<R> ): Response<R> {
if (this._err) {
return Response.err(this._err) as Response<R>;
}
return func(this);
}
async bindAsync<R>(func: (res: Response<T>) => Promise<Response<R>>): Promise<Response<R>> {
if (this._err) {
return Response.err(this._err) as Response<R>;
}
return await func(this);
}
divide(): HandleResponse<T> {
if (this._data) return [null, this._data];
return [this._err as Err, null];
}
}
Use case example:
// ...
async function chaining() {
const addTen = async (res: Response<number>) => {
const num = res.data() as number;
return Response.success(num + 10);
}
return Response.success(5)
.bindAsync(addTen)
}
async function chainingMoreThanOne() {
const addTen = async (res: Response<number>) => {
const num = res.data() as number;
return Response.success(num + 10);
}
return Response.success(5)
.bindAsync(addTen)
.bindAsync(addTen) // Here you got a error
}
main()
And the error is:
Property 'bindAsync' does not exist on type 'Promise<Response<createProductDTO>>'.
How would I do this bindAsync
in a way that a can chain it indefinetily?
====================================================================================================================================
5