lua-language-server
lua-language-server copied to clipboard
The type of keys used to index [] tables is not checked
How are you using the lua-language-server?
Visual Studio Code Extension (sumneko.lua)
Which OS are you using?
Windows
What is the issue affecting?
Type Checking
Expected Behaviour
Some warning should be raised if you use [5] on a table<string, x>, for example.
Actual Behaviour
In the expression tbl[x]
, the type of x is not checked at all
Reproduction steps
---@type table<integer, string> -- or string[]
local IntStr = {}
---@type table<string, integer>
local StrInt = {}
IntStr[5] = "hi" -- ok
IntStr["a"] = "b" -- "a" should produce a warning
StrInt["a"] = 5 -- ok
StrInt[5] = 6 -- 5 should produce a warning
Additional Notes
Probably related to #1861
Log File
No response
+1 for supporting this, it is especially annoying if you have a table that is supposed to be indexed by an enum, e.g.,
---@type table<"foo"|"bar", number>
local foo
foo["wrong value"] = 5 -- should be an error
+1 This seems to be a very core feature that has been missing for awhile.
+1 this would be very good!!!
Since this has now gotten attention from @sumneko I think it's worth pointing out another very similar issue that can potentially be solved by this. That is, similar challenges with using the ---@param [some_literal] ...
, and also with the ---@field
..
Currently, there is no way for "fields" on classes that are enums (or any literal, really) to actually be defined as mandatory. Or any literal, for that matter. It'll do proper type checking, but it will always work as if it was [<literal>]?
e.g.
---@class Foo
---@field [1] string
---@type Foo
x = {1} -- ✅ True negative
x = {'a'} -- ✅ True positive
x = {} -- ❌ False negative
For instance, we can't actually get checking on classes with fields that are enums (as @emmericp suggests).
Here's an example for params: