Skip to content

Commit

Permalink
feat: Add reponse types for typesafe returns
Browse files Browse the repository at this point in the history
  • Loading branch information
Konstantin committed Apr 11, 2020
1 parent 703848e commit f85f36a
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/response.ts
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
}
}

0 comments on commit f85f36a

Please sign in to comment.