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

FR: Allow 'self' return type to allow return type changing with inheritance

Open paul-reilly opened this issue 3 years ago • 2 comments

When annotating that one class has inherited from another, there is currently no way to annotate a function that returns it's current type that the current type should change when the class is inherited. Something along these lines, or something that accomplishes the same goal would be fantastic.

---@class Foo
Foo = {}

---@return self    --<-- 'self' refers to Foo so Foo.new() returns Foo
function Foo.new() end

---@class Bar : Foo
Bar = {}

local b = Bar.new() --<-- Bar.new() is inherited so the 'self' return type is now Bar
-- b should now be type Bar

Thanks!

paul-reilly avatar Aug 29 '22 10:08 paul-reilly

This is a bit of a hacky way around this for now:

---@class Foo
Foo = {}

---@return Foo
function Foo.new() end

---@class Bar : Foo
---@field new fun(): Bar
Bar = {}

local b = Bar.new()

By assigning the @field of new to a function that returns Bar, we are able to overwrite the return type.

carsakiller avatar Aug 29 '22 15:08 carsakiller

By assigning the @field of new to a function that returns Bar, we are able to overwrite the return type.

Thanks, that's definitely a lot better doing that once at the definition rather than casting and overriding warnings when creating objects.

paul-reilly avatar Aug 29 '22 16:08 paul-reilly

The generic inheritance has not been implemented for the time being.

sumneko avatar Nov 03 '22 09:11 sumneko