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

The type of keys used to index [] tables is not checked

Open mycroftjr opened this issue 10 months ago • 4 comments

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

mycroftjr avatar Apr 13 '24 06:04 mycroftjr

+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

emmericp avatar Apr 13 '24 13:04 emmericp

+1 This seems to be a very core feature that has been missing for awhile.

Riddle1001 avatar Jun 21 '24 03:06 Riddle1001

+1 this would be very good!!!

MillhioreBT avatar Jun 21 '24 14:06 MillhioreBT

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: image

bavalpey avatar Jun 26 '24 23:06 bavalpey