Adobe's ExtendScript features the UnitValue type, representing an on-screen distance. It is a type which is similar to, but distinct from, the Number type.
- Each
UnitValueobject carries atypestring, for example"cm"or"ft". - Arithmetic operations between
UnitValueobjects carrying differenttypevalues involves an implicit coercion; arithmetic operations between aUnitValueobject and a plainNumberhappens as-is, returning aUnitValue. - Each
UnitValueobject carries a number of miscellaneous fields; theUnitValueprototype implements a bunch of methods. - A
UnitValueobject is built from a constructor -var x = UnitValue(4, "cm").
How could I best represent this in TypeScript?
One way of implementing it - I chose centimeters as a base unit but you could use something else. It uses instance methods for arithmetic, as stated above you can't overload operators in TypeScript. I chose to maintain the type (unit) of the instance on which the method was called rather than the argument.
See comments in the code for explanation, but ask if you have any questions.
Used like this: