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
UnitValue
object carries atype
string, for example"cm"
or"ft"
. - Arithmetic operations between
UnitValue
objects carrying differenttype
values involves an implicit coercion; arithmetic operations between aUnitValue
object and a plainNumber
happens as-is, returning aUnitValue
. - Each
UnitValue
object carries a number of miscellaneous fields; theUnitValue
prototype implements a bunch of methods. - A
UnitValue
object 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: