I have a Dictionary with a fixed set of keys. Each key has an associated type, which is either Float or Number. I can declare it as
typedef MyDict as { :foo as Float, :bar as Number, :baz as Number };
And now d[:foo] has type Float?, and d[:bar] has type Number?, as I want.
But code like this:
function f(s as Symbol, d as MyDict) as Float? {
var v = d[s];
if (v == null) return null;
return v.toFloat();
}
won't compile, because v is Any. As far as the compiler is concerned, MyDict might contain additional keys which are unconstrained (in fact, it can't - I've fully specified all the keys it will ever contain).
So instead I can try
typedef MyDict as Dictionary<Symbol, Number or Float>;
and now the f above compiles, because both Number and Float support toFloat. But I can no longer pass d[:foo] to a method expecting a Float?, because the compiler doesn't know anything about specific keys.
Is there a better way to handle this? It would be nice to be able to specify both behaviors...