# NamedTuples in Type Constructors

**URL:** https://discourse.julialang.org/t/namedtuples-in-type-constructors/12251
**Category:** General Usage
**Created:** [July 8, 2018, 2:52pm UTC](https://discourse.julialang.org/t/namedtuples-in-type-constructors/12251 "2018-07-08T14:52:26Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![MLackner](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mlackner/32/2789_2.png) [@MLackner](https://discourse.julialang.org/u/MLackner)
#### Post date: [July 8, 2018, 2:52pm UTC](https://discourse.julialang.org/t/namedtuples-in-type-constructors/12251/1 "2018-07-08T14:52:27Z")

</div>

Hey!

I’m trying to do some type constructing with NamedTuple fields in 0.7beta. Here’s my problem:

```julia
julia> struct MyStruct x::NamedTuple{(:a,:b), Tuple{Real,Real}} end

julia> MyStruct(x::NamedTuple{(:b,), Tuple{Real,}}) = MyStruct((a=1, b=x[:b]))
MyStruct

julia> MyStruct((a=1, b=3))
MyStruct(NamedTuple{(:a, :b),Tuple{Real,Real}}((1, 3)))

julia> s = MyStruct((b=3,))
ERROR: MethodError: Cannot `convert` an object of type NamedTuple{(:b,),Tuple{Int64}} to an object of type NamedTuple{(:a, :b),Tuple{Real,Real}}
Closest candidates are:
  convert(::Type{NamedTuple{names,T<:Tuple}}, ::NamedTuple{names,T<:Tuple}) where {names, T<:Tuple} at namedtuple.jl:107
  convert(::Type{NamedTuple{names,T<:Tuple}}, ::NamedTuple{names,T} where T<:Tuple) where {names, T<:Tuple} at namedtuple.jl:111
  convert(::Type{T}, ::T) where T at essentials.jl:123
  ...
Stacktrace:
 [1] MyStruct(::NamedTuple{(:b,),Tuple{Int64}}) at ./REPL[32]:1
 [2] top-level scope at none:0

```

I really don’t get why this should throw an error.

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [July 8, 2018, 4:16pm UTC](https://discourse.julialang.org/t/namedtuples-in-type-constructors/12251/2 "2018-07-08T16:16:03Z")

</div>

I think you want something l like

```julia
MyStruct(x::NamedTuple{(:b,), T}) where {T <: Tuple{Real,}} =
    MyStruct((a=1, b=x[:b]))

```

also note that

```julia
julia> (b=3,) isa NamedTuple{(:b,), Tuple{Real,}}
false

julia> (b=3,) isa NamedTuple{(:b,), <:Tuple{Real,}}
true

```

[This explanation](https://docs.julialang.org/en/latest/manual/types/#Parametric-Composite-Types-1) may help.

Also, for similar reasons, you may want to [avoid `struct`s with abstract typed fields](https://docs.julialang.org/en/latest/manual/performance-tips/#Type-declarations-1), and use

```julia
struct MyStruct{T <: Tuple{Real,Real}}
    x::NamedTuple{(:a,:b), T}
end

```
