Skip to content

Instantly share code, notes, and snippets.

@alessioprestileo
Last active April 23, 2021 15:13
Show Gist options
  • Save alessioprestileo/94619a14e963a940e5a43afd27f37a57 to your computer and use it in GitHub Desktop.
Save alessioprestileo/94619a14e963a940e5a43afd27f37a57 to your computer and use it in GitHub Desktop.
Type-safe calculations using different units of measurement
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