Skip to content

meta | doc/meta- type annotation in different file #3071

@AgatZan

Description

@AgatZan

I see two ways: it is not well-documented or it is not provided, as I think. Or I just a duplicate these

Given: Lua file with classes (or just functions, maybe even local) without type annotations.
Needed: Create type annotations to provide suggestions, etc.

Maybe I'm wrong, but I think changing files that contain classes is a bad idea because it mixes the logic of the type with the flow of the program.

I didn't find a way to divide it.

I suggest it should look like

class_meta.lua or class.meta.lua

---@meta class

---@class MyClass
---@field a string
local MyClass = {}

---What it should do
---@param arg integer
---@return string
function MyClass:method(arg) end

return MyClass

class.lua

---@type MyClass | It should be inferred implicitly.
local MyClass = {}

function MyClass:method(arg) 
    return self.a .. arg 
end
return MyClass

But it is not working with the redefined error.

Then i try to use @overload annotation, but

+ ---@overload fun(self:MyClass, arg:integer):string

But it doesn't work either.

Also, there is a way to annotate all methods with @field, which makes initialization noisy and ugly, and doesn't give compilation suggestions for the method body. So, type annotations are needed again.

class.lua

local function method(self, arg)
    return self.a .. arg
end
---@type MyClass
local MyClass = {
    a = "", -- must init with default
    method = method
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions