Created
November 29, 2021 11:18
-
-
Save charlypoly/d3d8aff987b2f03ddbec98bad5891fa1 to your computer and use it in GitHub Desktop.
TypeScript Discriminated Unions with Template String types
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
interface Success { | |
type: `${string}Success`; | |
body: string; | |
} | |
interface Error { | |
type: `${string}Error`; | |
message: string; | |
} | |
function handler(r: Success | Error) { | |
if (r.type === "HttpSuccess") { | |
r | |
// `r` is of type `Success` | |
} else if (r.type === "NetworkError") { | |
r | |
// `r` is of type `Error` | |
} else if (r.type === "ServerError") { | |
r | |
// `r` is of type `Error` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment