Last active
April 23, 2021 15:13
-
-
Save alessioprestileo/94619a14e963a940e5a43afd27f37a57 to your computer and use it in GitHub Desktop.
Type-safe calculations using different units of measurement
This file contains hidden or 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
import {Feet, Meters, Measurement, toMeasurement} from './units-of-measurement'; | |
function area<T extends Measurement>(width: T, height: T): T { | |
return toMeasurement<T>(width * height); | |
} | |
const widthFeet = toMeasurement<Feet>(4); | |
const heightFeet = toMeasurement<Feet>(5); | |
const areaFeet = area<Feet>(widthFeet, heightFeet); | |
const widthMeters = toMeasurement<Meters>(4); | |
const heightMeters = toMeasurement<Meters>(5); | |
const areaMeters = area<Meters>(widthMeters, heightMeters); | |
const areaFailure1 = area<Feet>(widthFeet, heightMeters); // Error: Argument of type 'Meters' is not assignable to parameter of type 'Feet'. | |
const areaFailure2 = area<Meters>(widthFeet, heightMeters); // Error: Argument of type 'Feet' is not assignable to parameter of type 'Meters'. | |
const areaFailure3 = area<Feet>(4, 5); // Error: Argument of type 'number' is not assignable to parameter of type 'Feet'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment