Created
March 11, 2016 23:43
-
-
Save RikkiGibson/e43b12536ea709788b07 to your computer and use it in GitHub Desktop.
faking ADTs in TypeScript
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
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