Skip to content

Instantly share code, notes, and snippets.

@ratbeard
Created April 24, 2018 14:48
Show Gist options
  • Select an option

  • Save ratbeard/3cadc08268bd6b24513647d2f84f666e to your computer and use it in GitHub Desktop.

Select an option

Save ratbeard/3cadc08268bd6b24513647d2f84f666e to your computer and use it in GitHub Desktop.
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