# Typed globals: macro to define multiple, without manual type annotations

**URL:** <https://discourse.julialang.org/t/typed-globals-macro-to-define-multiple-without-manual-type-annotations/90818>\
**Category:** General Usage\
**Tags:** macros, typed-globals\
**Created:** [November 25, 2022, 4:46pm UTC](https://discourse.julialang.org/t/typed-globals-macro-to-define-multiple-without-manual-type-annotations/90818 "2022-11-25T16:46:59Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)\
**Post date:** [November 27, 2022, 11:38am UTC](https://discourse.julialang.org/t/typed-globals-macro-to-define-multiple-without-manual-type-annotations/90818/2 "2022-11-27T11:38:10Z")

</div>

Not sure if something like this is already in a package somewhere, but here’s one way to write such a macro:

```julia
function rewrite_assignment(@nospecialize(ex))
    if Meta.isexpr(ex, :(=))
        l, r = ex.args
        l isa Symbol || error("Destructuring not supported")
        tmp = gensym(l)
        return esc(:(let $tmp = $r; global $l::typeof($tmp) = $tmp end))
    elseif Meta.isexpr(ex, :block)
        return Expr(:block, Base.mapany(rewrite_assignment, ex.args)...)
    else
        return ex
    end
end

macro typed(ex)
    return rewrite_assignment(ex)
end

```

```julia
julia> @typed begin
         a = 2
         b = 2.8
       end
2.8

julia> code_typed() do
           a, b
       end
1-element Vector{Any}:
 CodeInfo(
1 ─ %1 = Main.a::Int64
│ %2 = Main.b::Float64
│ %3 = Core.tuple(%1, %2)::Tuple{Int64, Float64}
└── return %3
) => Tuple{Int64, Float64}

```

---

_[View the full topic](https://discourse.julialang.org/t/typed-globals-macro-to-define-multiple-without-manual-type-annotations/90818)._
