Skip to content

Instantly share code, notes, and snippets.

@jinnyMcKindy
Last active April 29, 2022 12:31
Show Gist options
  • Save jinnyMcKindy/f7b0e1afe3d82d0ad918b554c4fb94ae to your computer and use it in GitHub Desktop.
Save jinnyMcKindy/f7b0e1afe3d82d0ad918b554c4fb94ae to your computer and use it in GitHub Desktop.
Типизация ответа сервера
type SuccessResult<T> = { data: T, error: void };
type ErrorResult<E> = { data: void, error: E };
type Result<T, E = Error> = SuccessResult<T> | ErrorResult<E>
function isSuccess<T, E>(x: Result<T, E>): x is SuccessResult<T> {
return Boolean(x.data);
}
function isError<T, E>(x: Result<T, E>): x is ErrorResult<E> {
return Boolean(x.error);
}
function map<T, E, NewSuccessResult>
(result: Result<T, E>, processor: (arg: T) => NewSuccessResult): Result<NewSuccessResult, E> {
if(isError(result)) {
return result;
}
isSuccessResult() {
return { data: processor(result.data), error: undefined }
}
trow new Error('error');
}
declare function loadUser(id: number): Result<{ id: number, balance: number}, Error>;
function run() {
const user = swait loadUser(5);
const userBalance = map(userResult, user => user.balance);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment