lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

Diagnostics.(param-type-mismatch)

Open RomanSpector opened this issue 3 years ago • 1 comments

---@enum Test
local Test = {
    Test1 = 1,
    Test2 = 2,
    Test3 = 2,
}

---@type Test|Test[]
local a

---@param c Test
local function b(c) end

if type(a) == "table" then
    b(a[1]);
else
    b(a);
end

---@class Class
---@field a Test|Test[]
local Class = {};

function Class:Test()
    if type(self.a) == "table" then
        b(self.a[1]);
    else
        b(self.a);
    end
end

image image

RomanSpector avatar Jul 31 '22 11:07 RomanSpector

The language server is not able to recognize that self.a is not a table and therefor not a Test[]. This can be solved by casting self.a to Test in the second case.

Unfortunately, there is no way to cast a Class field using @cast, but you can use @as

---@enum Test
local Test = {
    Test1 = 1,
    Test2 = 2,
    Test3 = 2,
}

---@type Test|Test[]
local a

---@param c Test
local function b(c) end

if type(a) == "table" then
    b(a[1]);
else
    b(a);
end

---@class Class
---@field a Test|Test[]
local Class = {};

function Class:Test()
    if type(self.a) == "table" then
        b(self.a[1]);
    else
        -- cast here!
        b(self.a --[[@as Test]]);
    end
end

carsakiller avatar Jul 31 '22 15:07 carsakiller