Skip to content

Instantly share code, notes, and snippets.

@kourge
Created January 19, 2017 02:45
Show Gist options
  • Save kourge/642a09eab7296fef75e3f7adada9ff4f to your computer and use it in GitHub Desktop.
Save kourge/642a09eab7296fef75e3f7adada9ff4f to your computer and use it in GitHub Desktop.
Type-safe units in TypeScript
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