LuaLS / LuaLS/lua-language-server

Feature Request: Capture table keys similar to capturing generic types

未關閉
#2,058 1 則留言 12 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

enhancement
主要語言
Lua
星號
4.4k
分支
442
PR 合併指標
30 天內沒有已合併 PR

描述

I like [TypeScript's `keyof` operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html) that basically suggests that the value of a given string must match one of the properties/keys of a specified object.

In Lua, a type declared as `@type keyof queries` would mean it is a string whose value is a key found in the `queries` table.

This is useful because I can change just the value types if the keys of a table parameter were to be captured and specified as the target for a returned table type.

Here's an example of what I currently have to show the problem:

```lua
---@param queries table
---@return table
local function QueryMany(queries)
local results = {}

for key, query in pairs(queries) do
results[key] = Query(query) -- this function returns `QueryResult?`
end

return results
end
```

So, you can see that the `queries` argument is a table, and the keys should be exactly the same in the returned table, but only the values change.

Therefore, when I hover over the returned table in VS Code it doesn't know the keys in the table and only shows the key as being a string.

In the example above, the new annotation would look like this:

```lua
---@param queries table
---@return table
```

Currently, I need to create custom aliases or cast the returned tables manually when using the `QueryMany` example function to add the desired intelli-sense in VS Code. This is a problem because the function is designed to be dynamically reusable with arbitrary table arguments.

For context, this is how I would use the above function:
```lua
local results = QueryMany({
xSpacing = "frame.dimensions.xSpacing",
ySpacing = "frame.dimensions.ySpacing",
vDirection = "frame.behavior.vDirection",
hDirection = "frame.behavior.hDirection",
})
```
(**in summary:** _the table is transformed from a key-value pair of `string`/`string` to `string`/`QueryResult?` and there is no way of telling LuaLS this without losing the field/key names_)

You could also support `keyof` for standard aliases and types:

```lua
---@type keyof queries
local queryName = "" -- the value of queryName must match a field key found in the queries table

-- or as an alias:
---@alias QueryName keyof queries
```

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

該 issue 未指定任何 repository 檔案、測試或進入點。首先定位現有的泛型捕獲和註解處理,然後追蹤表格鍵和別名的表示方式。當 `keyof queries` 為返回的表格保留輸入表格的鍵,並根據這些鍵驗證獨立值或別名時,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
lua
領域
devtools
Issue 類型
功能
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。