-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add reponse types for typesafe returns
- Loading branch information
Konstantin
committed
Apr 11, 2020
1 parent
703848e
commit f85f36a
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
export type Response<T, E> = Valid<T, E> | Err<T, E> | ||
|
||
export const valid = <T, E>(value: T): Valid<T, E> => new Valid(value) | ||
export const err = <T, E>(error: E): Err<T, E> => new Err(error) | ||
|
||
export class Valid<T, E> { | ||
constructor(readonly value: T) {} | ||
|
||
public isValid(): this is Valid<T, E> { | ||
return true | ||
} | ||
|
||
public isError(): this is Err<T, E> { | ||
return !this.isValid() | ||
} | ||
|
||
public getValue(): T { | ||
return this.value | ||
} | ||
|
||
public getError(): E { | ||
throw new Error('Tried to get error from a success.') | ||
} | ||
} | ||
|
||
export class Err<T, E> { | ||
constructor(readonly error: E) {} | ||
|
||
public isError(): this is Err<T, E> { | ||
return true | ||
} | ||
|
||
public isValid(): this is Valid<T, E> { | ||
return !this.isError() | ||
} | ||
|
||
public getValue(): T { | ||
throw new Error('Tried to get success value from an error.') | ||
} | ||
|
||
public getError(): E { | ||
return this.error | ||
} | ||
} |