Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlypoly/d3d8aff987b2f03ddbec98bad5891fa1 to your computer and use it in GitHub Desktop.
Save charlypoly/d3d8aff987b2f03ddbec98bad5891fa1 to your computer and use it in GitHub Desktop.
TypeScript Discriminated Unions with Template String types
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