0

In TypeScript, I would like the convenience of normal arithmetic operations:

const totalWeight = baseWeight + loadWeight

But I would like to prevent accidentally mixing units.

I tried something naive:

type Ounce = number;
type Gram = number;
const x: Ounce = 1;
const y: Gram = 2;
x + y;

... hoping it would give me a type error, but it didn't.

Is there a way to achieve this? Bonus credits if it could validate const s: Velocity = distance / time

slim
  • 40,215
  • 13
  • 94
  • 127
  • See also e.g. https://stackoverflow.com/q/49260143/3001761. – jonrsharpe Apr 01 '22 at 16:13
  • Your "bonus credits" line at the end would need a decent amount of work to achieve. The best you could get is `divide(distance, time)` (there's nothing we can do to numeric operators like `/` here) and have some kind of mass/length/time exponent counter inside our dimension types. Seems fun but out of scope for a "bonus". – jcalz Apr 01 '22 at 16:16
  • Maybe something like [this](https://tsplay.dev/N7OboN) for the bonus? – jcalz Apr 02 '22 at 20:06

0 Answers0