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

How do I annotate an imported global?

Open UtkarshVerma opened this issue 1 year ago • 2 comments

I have the following use case. There's a library that defines a global vim.g as table<string, any>. In my application code, I want to utilise only the "autoformat" key of that table, i.e. vim.g.autoformat. I want to enforce this key as a boolean? but the language server marks it as any.

Is there any way I could achieve this?

UtkarshVerma avatar Jan 24 '24 07:01 UtkarshVerma

Unfortunately I've yet to find a solution that doesn't cost anything in performance, but there's two tricks I've used.

If I'm annotating a provided global, I use

---@type MyAwesomeType
Global = Global or {}

If I'm annotating an imported library, I use

local lib = require("my.awesome.library")

if false then
  lib = {}

  ---@param someparameter SomeType
  lib.somefunction = function (someparameter)

  end
end

return lib

Of course, what you use is up to you. I've found the second approach works best with complicated library functions like those that 30log provide, as well as any generics.

There's a tiny bit of performance loss, but IMO it's worth it

oezingle avatar Feb 06 '24 01:02 oezingle

It works but is a bit hacky. Hopefully, we'll have a better solution for this.

UtkarshVerma avatar Feb 13 '24 06:02 UtkarshVerma