Created
April 24, 2018 14:48
-
-
Save ratbeard/3cadc08268bd6b24513647d2f84f666e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| interface ErrorResponse { | |
| errorMessage: string; | |
| redirectUrl?: string; | |
| } | |
| interface SessionResponse { | |
| username: string; | |
| email: string; | |
| } | |
| function fetchSession(): Promise<SessionResponse | ErrorResponse> { | |
| return fetch('/session').json() | |
| } | |
| async function bootUpDaApp() { | |
| // .ts treats response as SessionResponse | ErrorResponse here. | |
| // Would need to cast w/ `as` normally. | |
| const response = await fetchSession() | |
| if ('errorMessage' in response) { | |
| // Since this property is only in one of the types, | |
| // .ts treats response as ErrorResponse in this block. | |
| alert(response.errorMessage) | |
| return | |
| } | |
| // Based on the handling / return above, .ts treats response as SuccessResponse | |
| // from here on out! | |
| document.body = `Welcome home, ${ response.username }` | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment