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

[Future Ruquest] An easy way to create a partial of a class

Open uga-rosa opened this issue 1 year ago • 2 comments

I want a generics equivalent to Partial<T> in TypeScript.

When creating some extension in lua, the user should write only the parts that they want to change from the default settings in order to configure it. Internally, however, the user settings are merged with the default settings to create a configuration table with no missing field. In this case, I am not happy to have to define these two classes separately, because it can cause bugs due to synchronization errors.

local M = {}

---@class Config
---@field foo string
---@field bar number
M.options = {}

---@type Config
default = {
  foo = "foo",
  bar = 1,
}

---@class Config.P
---@field foo? string
---@field bar? number

---@param opts Config.P
local function setup(opts)
  M.options = tbl_merge(default, M.options, opts)
  -- ...
end

uga-rosa avatar Mar 08 '24 03:03 uga-rosa

It seems currently the diagnostic for missing fields does not take into account inheritance so I end up doing what you do here but instead of redefining every field I use ---@class Config.P: Config. The convention implies everything is optional (the hover/intellisense doesn't) and you do not receive a warning on "missing" fields.

This also means that abusing this bug and enabling something like a generic inheritance ---@class Optional<T>: T would be great, this is currently not possible though.

I think following recent updates in LuaLS we could end up with a suffix for the @param fields to disable such warnings. Like: ---@param(partial) opts Config

vallode avatar May 15 '24 08:05 vallode

Having something to mark a type's (or class's) fields as optional is sorely needed. Otherwise, you have to go and recreate/redefine it several times, which is just not feasible especially if you have more than a few fields. My use-case is similar to yours.

It seems currently the diagnostic for missing fields does not take into account inheritance

I came across that recently too. Definitely a bug imo.

tmillr avatar Aug 04 '24 05:08 tmillr