Created
September 17, 2020 14:22
-
-
Save CallumVass/175baf84382b3efd876c5c4c0b649477 to your computer and use it in GitHub Desktop.
TS/F#
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
export interface ErrorValue { | |
ErrorValue: string; | |
} | |
export interface ResultValue<T> { | |
ResultValue: T; | |
} | |
export interface ErrorResult { | |
Case: "Error"; | |
Fields: ErrorValue; | |
} | |
export interface OkResult<T> { | |
Case: "Ok"; | |
Fields: ResultValue<T>; | |
} | |
export type Result<T> = OkResult<T> | ErrorResult; | |
export const handleResultType = <T>( | |
data: Result<T>, | |
okCallBack: (_: T) => void, | |
errorCallBack: (_: string) => void | |
) => { | |
switch (data.Case) { | |
case "Ok": | |
return okCallBack(data.Fields.ResultValue); | |
case "Error": | |
return errorCallBack(data.Fields.ErrorValue); | |
} | |
}; | |
//usage | |
login() | |
.then((response) => response.json() as Promise<Result<Token>>) | |
.then((data) => { | |
handleResultType( | |
data, | |
(okValue: Token) => { | |
console.log("OK", okValue); | |
}, | |
(error) => { | |
console.log("ERROR", error); | |
} | |
); | |
}); |
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 CreateUserRequest = | |
{ Email: string | |
Password: string | |
PasswordConfirmation: string } |
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 CreateUserRequest = { | |
Email: string; | |
Password: string; | |
PasswordConfirmation: string; | |
}; |
Thanks, that looks a lot cleaner 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you want to go the full promise way I'd suggest something like this in the
handleResultType
it should work somewhat like this (just wrote it from memory didn't test it)
and it also should save you from nesting callbacks