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

Generic record values cannot be used as generic interface type #859

Open
svermeulen opened this issue Nov 23, 2024 · 0 comments
Open

Generic record values cannot be used as generic interface type #859

svermeulen opened this issue Nov 23, 2024 · 0 comments

Comments

@svermeulen
Copy link
Contributor

Example below:

-- Not using generics works as expected:

-- local interface IFoo
--    get_value: function(self): integer
-- end

-- local record Foo is IFoo
--    _value: integer
-- end

-- function Foo:get_value():integer
--    return self._value
-- end

-- function Foo.new(value: integer):Foo
--    local fields = { _value = value }
--    return setmetatable(fields, { __index = Foo })
-- end

-- local function create_foo(value: integer):IFoo
--    local foo = Foo.new(value)
--    return foo
-- end

------------------------

-- But with generics we get error:
-- "in return value: got Foo<T>, expected interface IFoo"
-- in create_foo function

local interface IFoo<T>
   get_value: function(self): T
end

local record Foo<T> is IFoo<T>
   _value: T
end

function Foo:get_value():T
   return self._value
end

function Foo.new(value: T):Foo<T>
   local fields = { _value = value }
   return setmetatable(fields, { __index = Foo })
end

local function create_foo<T>(value: T):IFoo<T>
   local foo = Foo.new(value)
   return foo

   -- Have to do this instead for now:
   -- return foo as IFoo<T>
end

------------------------

local foo = create_foo(5)
print(foo:get_value())
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

1 participant