Skip to content

Instantly share code, notes, and snippets.

@CVertex
Created August 25, 2018 12:42
Show Gist options
  • Save CVertex/dd05905fca64376768a49c26cdcfe631 to your computer and use it in GitHub Desktop.
Save CVertex/dd05905fca64376768a49c26cdcfe631 to your computer and use it in GitHub Desktop.
Discriminated Union TypeScript example using instanceof. It's nice for web APIs
class Video {
id: number;
constructor(id: number) {
this.id = id;
}
}
class Error {
message: string;
constructor(message: string) {
this.message = message;
}
}
// This function takes a discriminated union, it is either an Error or Video
// This allows us to API response types pretty clean
function processResult (input: Video | Error) {
var el = document.createElement("p");
if (input instanceof Error) {
var err = input;
el.innerText = "error" + input.message;
} else if (input instanceof Video) {
el.innerText = "thing:" + input.id;
}
document.body.appendChild(el);
}
processResult(new Video(12));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment