Created
October 23, 2023 11:37
-
-
Save pedrovasconcellos/74be94a7094577301649b8df16bc42cd to your computer and use it in GitHub Desktop.
Result T in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type StringMap = Map<string, string>; | |
export class ResultT<T> { | |
value: T | null; | |
errors: StringMap; | |
constructor() { | |
this.value = null; | |
this.errors = new Map<string, string>(); | |
} | |
static new<T>(): ResultT<T> { | |
return new ResultT(); | |
} | |
static withValue<T>(value: T): ResultT<T> { | |
const result = new ResultT<T>(); | |
result.value = value; | |
return result; | |
} | |
static withErrors<T>(errors: StringMap): ResultT<T> { | |
const result = new ResultT<T>(); | |
result.errors = errors; | |
return result; | |
} | |
static withValueAndErrors<T>(value: T, errors: StringMap): ResultT<T> { | |
const result = new ResultT<T>(); | |
result.value = value; | |
result.errors = errors; | |
return result; | |
} | |
static withValueAndError<T>(value: T, parameterError: string, error: string): ResultT<T> { | |
const result = new ResultT<T>(); | |
result.value = value; | |
result.errors.set(parameterError, error); | |
return result; | |
} | |
addError(parameter: string, error: string): this { | |
this.errors.set(parameter, error); | |
return this; | |
} | |
containsErrorDescription(errorDescription: string): boolean { | |
for (const error of this.errors.values()) { | |
if (error === errorDescription) { | |
return true; | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment