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

[Feature request] User defined type guards like TypeScript's one

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

As a simple example, I would like to annotate the following @guard x string. This is in effect returning a boolean, which narrows down the type of the argument x.

---@param x unknown
---@guard x string
local function isString(x)
  return type(x) == "string"
end

---@param x string | number
local function main(x)
  if isString(x) then
    -- x is string
    print(x)
  else
    -- x is number
    print(x)
  end
end

uga-rosa avatar Jan 11 '24 13:01 uga-rosa

I'd like this feature as well. It's been proposed a couple of times in the past, but it's apparently hard to implement: https://github.com/LuaLS/lua-language-server/issues/1030#issuecomment-1156378355

firas-assaad avatar Jan 12 '24 17:01 firas-assaad