How to get the non-Nothing type from `Union{T,Nothing}`

If I define

const Maybe{T} = Union{T,Nothing}

How to “pop” the T type from Maybe? I want to do this because I have the following type

using Parameters

@with_kw struct A
    a::Maybe{String} = nothing
    b::Maybe{Float64} = nothing
    c::Maybe{Int} = nothing
    d::Int = 1

I want to parse this type from matched strings by

[parse(fieldtype(A, f), match(regex, str)[1]) for (f, regex) in zip(fieldnames(A), REGEXES)]

where each field f is associated with a regex.

Of course, I can use setdiff to kick Nothing out of that Maybe. But the code looks ugly…

Another problem is that I cannot parse a String from a String, but that is not a big deal.

There is ‘nonmissingtype’ that does this for ’Missing’. You could look at it’s definition and do the same for ‘Nothing’.


Hmmm. It is the first time I heard about this function. It uses Core.Compiler.typesubtract. Thank you.

A poor man’s nonnothingtype:

nonnothingtype(::Type{T}) where {T} = Core.Compiler.typesubtract(T, Nothing)

I did a little bit search and found some links, hope this would help others:

  1. Get non-missing type in the case of parametric type
  2. Base.nonmissingtype and Core.Compiler.typesubtract aren't exported
  3. Dispatch using Union and order of arguments