Iterating over types in Union

Is there a way (that doesn’t involve reaching into private details of Base/Core) to iterate over the types in a Union? In my case I know that it’ll only ever be a small union of concrete types, if that helps.

I’m writing a library to do REST API interaction and I have a Dict holding information on each endpoint. This includes a return type (Julia type) for that endpoint. The server returns JSON which is parsed into a Dict and then converted into the expected return type.

Except that exactly one of 200 endpoints can return two different types of data. So I have the return type as Union{A, B} and want to convert the returned Dict into either A or B, as appropriate.

Is it possible to write code something like this?

for type in return_types
    can_convert_to(type, returned_data) && return type(returned_data)
julia> Base.uniontypes(Union{Int,Float64})
2-element Vector{Any}:

good enough? It does go into Base, but the function name doesn’t start with an _ which is a little better.


I’d like to piggyback off of Dan’s answer - that’s exactly what I’d recommend as well. In my own package I’ve taken the same approach to parse & convert path parameters so I could pass them directly to a request handler.

Here’s the function with that union iteration:

Here’s an example of it in action:

1 Like

I feel heartened that you are using this in a package like Oxygen. Not ideal to be using undocumented functions but it’s probably the best option for me.