lua-language-server
lua-language-server copied to clipboard
Diagnostics.(param-type-mismatch)
---@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

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