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

Way to annotate @overload only table, instead of the entire @class #2826

Open
d-enk opened this issue Aug 27, 2024 · 2 comments
Open

Way to annotate @overload only table, instead of the entire @class #2826

d-enk opened this issue Aug 27, 2024 · 2 comments

Comments

@d-enk
Copy link

d-enk commented Aug 27, 2024

---@class Class
---@overload fun(): self|Class
local Class = {}

local c = Class()

local unknown = c() -- but unknown is Class

I thought that was the indication self/Class was responsible for this

self for object
Class for table

But today I discovered that this is not so.
And in previous versions as well

In principle, this can be achieved by explicitly making

---@cast Class Class|fun(): Class

But for long names it is extremely monstrous

@tomlau10
Copy link
Contributor

I found a way to do it:

---@class Class
local Class = {}    ---@type fun(): Class

local c = Class()   --> Class
local a = c()       --> unknown

However in the above case the local Class will be table|fun():Class only. That means in the following code:

---@class Class
---@field c integer
local Class = {}    ---@type fun(): Class

function Class:a()
    self. --< trigger auto complete here, it will not suggest `.c` field, because `self` is just `table` type not `Class`
end

If you need it to be Class instead of table, you need to write:

---@class Class
---@field c integer
local Class = {}    ---@type Class|fun(): Class

function Class:a()
    self. --< now it will suggest `.c` field here
end

---@cast Class Class|fun(): Class
But for long names it is extremely monstrous

In addition, the @cast supports [+|-]<type> syntax. So in your original method, you can write:

---@cast Class +fun(): Class

So at best only 1 Class less 😅
If you really want to distinguish between a class and an instance, maybe you should create 2 classes Class and Class.instance in the first place 🤔 And only Class have the overload to return a Class.instance. That way a Class.instance will not have the function call type.

@d-enk
Copy link
Author

d-enk commented Aug 27, 2024

In addition, the @cast supports [+|-] syntax.

That's what I needed, thank you, I completely forgot that there is a [+|-]<type> syntax

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants