Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mycroftjr opened this issue Apr 13, 2024 · 4 comments
Open

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

mycroftjr opened this issue Apr 13, 2024 · 4 comments
Labels
bug Something isn't working

Comments

@mycroftjr
Copy link

mycroftjr commented Apr 13, 2024

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

@emmericp
Copy link
Contributor

+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

@Riddle1001
Copy link

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

@MillhioreBT
Copy link

+1 this would be very good!!!

@bavalpey
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

6 participants