-
-
Save blemoine/b1fb2f8aa6ad51d755c27bb446eb051a to your computer and use it in GitHub Desktop.
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
declare class MeterTag { | |
private __kind: 'meter' | |
} | |
type Meter = number & MeterTag; | |
declare class FootTag { | |
private __kind: 'foot' | |
} | |
type Foot = number & FootTag | |
function createMeter(value: number): Meter { | |
//This *must* be the only way to create a Meter | |
return value as Meter; | |
} | |
function createFoot(value: number): Foot { | |
//This *must* be the only way to create a Foot | |
return value as Foot; | |
} | |
function fromFootToMeter(feet: Foot): Meter { | |
return createMeter(0.3048 * feet); | |
} | |
function move(m:Meter) { | |
console.log('move', m, 'meter'); | |
} | |
const distance1 = createMeter(10); | |
const distance2 = createFoot(10); | |
move(distance1) // compile | |
move(distance2) // Argument of type Foot is not assignable to Meter | |
move(fromFootToMeter(distance2)) // compile | |
move(distance1 + distance2) | |
// Argument of type number is not assignable to Meter, the tag is lost |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment