Created
January 19, 2017 02:45
-
-
Save kourge/642a09eab7296fef75e3f7adada9ff4f to your computer and use it in GitHub Desktop.
Type-safe units 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
namespace TypeBranding { | |
// This incurs no runtime cost. It is a purely compile-time construct. | |
type Meters = number & { __metersBrand: any }; | |
type Miles = number & { __milesBrand: any }; | |
function Meters(i: number): Meters { return i as Meters; } | |
function Miles(i: number): Miles { return i as Miles; } | |
let a: Meters; | |
a = 5; // does not compile | |
a = Miles(5); // does not compile | |
a = Meters(5); // compiles | |
} | |
namespace InterfacePlusLiteralTypes { | |
interface Distance<Unit extends string> { | |
value: number; | |
unit: Unit; | |
} | |
type Meters = Distance<'meters'>; | |
type Miles = Distance<'miles'>; | |
function Meters(value: number): Meters { return {value, unit: 'meters'}; } | |
function Miles(value: number): Miles { return {value, unit: 'miles'}; } | |
let a: Meters; | |
a = 5; // does not compile | |
a = Miles(5); // does not compile | |
a = Meters(5); // copiles | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment