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

No Protection on enum values as function input

Open GiuseppeIII opened this issue 2 years ago • 2 comments

Currently with code like the following:

---@enum TestEnum
TestEnum = {
	ONE = "ONE",
	TWO = "TWO",
	THREE = "THREE",
}

---@param test_enum TestEnum
local function test(test_enum)
	print(test_enum)
end

test(TestEnum.ONE) --- CORRECT: No error
test("ONE") --- CORRECT: No error
test(TestEnum.FOUR) --- INCORRECT: No error
test("FOUR") --- CORRECT: Error

There is no intellisense error for test(TestEnum.FOUR) like there is for test("FOUR")

Screenshot_1

It would be nice to get an error if you are trying to use a non-existing enum value (I have run into problems relating to this 😞) similarly if you are trying to use a string literal which doesn't match the enum.

I think this might be related to a wider issue where inputs to functions can be of type unknown even with the no-unknown setting.

GiuseppeIII avatar Oct 22 '23 22:10 GiuseppeIII

Workaround:

---@class ColorsContainer
local COLORS = --[[@enum Colors]] {
    RED = "Red",
}

---@param color Colors
local function setColor(color)
    error("nyi")
end

setColor(COLORS.RED) -- allowed
setColor(COLORS.REDDER) -- yellow squiggle

image

LunNova avatar Jun 28 '24 23:06 LunNova

duplicate of https://github.com/LuaLS/lua-language-server/issues/1750

I guess this is because the undefined field check is only done for typed table, and ---@enum doesn't treat the binded table as typed (it's creating an alias of union of all the values under the hood)

tomlau10 avatar Jun 29 '24 08:06 tomlau10