Closed
Description
Reproducer:
function get_field_type(::Type{T}, field::Symbol) where {T <: NamedTuple}
names = fieldnames(T)
types = fieldtypes(T)
index = findfirst(==(field), names)
if index === nothing
throw(ArgumentError("Field $field not found"))
end
types[index]
end
function get_field_type(nt::NamedTuple, field::Symbol)
get_field_type(typeof(nt), field)
end
function f(nt)
get_field_type(nt, :a)
end
Core.Compiler.return_type(f, Tuple{typeof((; a = 1))}) # inference fails: `DataType`
Core.Compiler.return_type(f, Tuple{typeof((; a = 1, b = 2))}) # OK: `Type{Int64}`
This comes from Discourse: https://discourse.julialang.org/t/constant-propagation-with-a-namedtuple-with-one-field/121887
Both return types were inferred as Type{Int64}
back in v1.9.