[New solver] could be nil in for loop

type TypeA = {Value: any}

local list = {} :: {[string]: TypeA?}

for index, a in list do
	a.Value = 1
end

if i use TypeA? to force if checks when accessing the list for example

local a = list["index"]
a.Value -- this will show a type error correctly as it might be nil

but when in a for loop there is 0% chance the value could ever be nil so it should remove the ?

Yes please I have been recently bothered by this too


Hello! I am pretty sure you’re right here, in that if we see a table with an indexer, and we iterate over said table, we should be able to guarantee that the values are non-nil. There might be some edge cases with metatables, but regardless we’ll keep you in the loop with what we do here.

Hello! Sorry for the delay, and to report that we are probably not going to be fixing this in the near future. As mentioned, there was some chance of metatable corner cases making this unsafe to do, which is true:

function list_iter(t: { number })
    local i = 0
    local n = #t
    return function (): (number?, number?)
        i = i + 1
        if i > n then
            return nil, nil
        end
        local val = t[i]
        return i, if val % 2 == 0 then val else nil

    end
end

local t = setmetatable({1, 2, 3}, { __iter = list_iter })

local function printAllNumbers(t: { number })
    for _, n in t do
        -- Despite the fact that we claim that `n` must be number here, it could
        -- be nil due to the interaction with generalized iteration
        print(n, typeof(n))
    end
end

printAllNumbers(t)

There is a little more going on here than just the issue you cited. It could be argued that the above should not type check at all, and there are even more confusing versions of the above that produce even weirder results.

For now, our recommendation is to not mark indexers as nil-able in this scenario.

Thanks for the report, this should now be resolved. Let us know if you experience any more issues!