Benjamin-Dobell / IntelliJ-Luanalysis

Type-safe Lua IDE — IntelliJ IDEA plugin
Apache License 2.0
155 stars 22 forks source link

There seems to be no way to define a non-nil generic return value for a function #152

Open pouwelsjochem opened 1 year ago

pouwelsjochem commented 1 year ago

Environment

Name Version
IDEA version 2022.3.1
Luanalysis version 1.4.0
OS MacOS

Lua

Name Setting
Language level 5.2

Type Safety

Name Setting
Strict nil checks ☑️
Unknown type (any) is indexable ☑️
Unknown type (any) is callabale ☑️

What are the steps to reproduce this issue?

Consider the following utility function:

---@generic T, R
---@param _array T[]
---@param _mapperFunction fun(obj:T, i:number):R
function array.mapAndFilter(_array, _mapperFunction)
    local mappedArray = {} ---@type R[]
    for i = 1, #_array, 1 do
        local mappedValue = _mapperFunction(_array[i], i)
        if mappedValue ~= nil then
            mappedArray[#mappedArray + 1] = --[[---@not nil]] mappedValue
        end
    end
    return mappedArray
end

What happens?

Calling this function effectively returns an array of R where R is never nil. At the moment there seems to be no way to let Luanalysis deduce R can never be nil. I think defining the return value of _mapperFunction as (R|nil) could be a nice way to say R can never be nil.