Skip to content

Instantly share code, notes, and snippets.

@RikkiGibson
Created March 11, 2016 23:43
Show Gist options
  • Save RikkiGibson/e43b12536ea709788b07 to your computer and use it in GitHub Desktop.
Save RikkiGibson/e43b12536ea709788b07 to your computer and use it in GitHub Desktop.
faking ADTs in TypeScript
type Meters = { meters: number };
type Feet = { feet: number };
type Distance = Meters | Feet;
function isMeters(distance: Distance): distance is Meters {
return typeof (distance as Meters).meters === 'number';
}
function isFeet(distance: Distance): distance is Feet {
return typeof (distance as Feet).feet === 'number';
}
function checkDistance(x: Distance): string {
if (isMeters(x)) {
return "meters";
} else if (isFeet(x)) {
return "feet";
}
return "neither";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment