I am modelling widths for table cells. Widths can be an number or the special value “auto”. A bit like css.
For the value “auto” I can use a string but it’s too board.
What I want is a unit or literal type. In Crystal I don’t actually need anything special. I can do this:
class Auto
end
alias Width = Int32 | Auto
cell(width: 5)
cell(width: Auto.new)
This is ok but structs and a singleton is probably better
struct Auto
INSTANCE = self.allocate
def self.new
INSTANCE
end
end
cell(width: Auto.new) # is now a singleton?
or maybe a enum of one, just a bit annoying to have the double name
enum Auto
Auto
end
alias Width = Int32 | Auto
cell(width: :auto) # auto casting is nice
What I don’t like is the verbosity. Like record is a built in macro I wondering what people think about adding a macro for unit types and the performance implication for modelling things like this?
macro unit(*names)
{% for name in names %}
enum {{name.id}}
{{name.id}}
end
{% end %}
end
unit Auto, None
alias Width = Int32 | Auto | None # type safe!
I’ve read other threads on suggesting adding literal types like in typescript. This is not that.