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

---@param queries table<string, string>
---@return table<string, QueryResult?>
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:

---@param queries table<string, string>
---@return table<keyof queries, QueryResult?>

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:

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:

---@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 摘要。