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

Proposal: Add @constructor Tag for Class Constructors in Lua LSP

Open ErickProgramer opened this issue 8 months ago • 1 comments

This Lua LSP could benefit from a new @constructor tag, which would be used when defining classes, especially with libraries. Currently, we have to do something like this:

---@class myCls
---@overload fun(a: integer, b: integer): myCls
local myCls = class "myCls"

---@param a integer
---@param b integer
function myCls:__init(a, b)
     self.a = a
     self.b = b
end
local instance = myCls(10, 20)
print(instance)

As you can see, we need to create an overload for the variable, which makes the typing process quite repetitive. To address this, we could introduce a new @constructor tag that would automatically handle this:

---@class myCls
local myCls = class "myCls" -- No need for an overload anymore.

-- Defining this method as the constructor:
---@constructor
---@param a integer
---@param b integer
function myCls:__init(a, b)
     self.a = a
     self.b = b
end
local instance = myCls(10, 20) -- Type checking would work correctly and show the constructor parameters.
print(instance)

This approach would make the code cleaner and more intuitive, reducing the need for repetitive annotations and improving the overall developer experience.

ErickProgramer avatar Feb 07 '25 16:02 ErickProgramer