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 functions not being typed correctly in generalized iteration? #1165

Open
MaximumADHD opened this issue Feb 14, 2024 · 0 comments
Open
Labels
bug Something isn't working

Comments

@MaximumADHD
Copy link
Contributor

Hopefully I'm describing this correctly? I'm not familiar with the terminology used for types at an implementation level.
Consider the following script:

--!strict
local Node = {}
Node.__index = Node

export type Node<T> = typeof(setmetatable({} :: {
    Value: T
}, Node))

local allNodes = {} :: { INode }
export type INode = Node<any>

function Node.new<T>(value: T): Node<T>
    local node = setmetatable({
        Value = value
    }, Node)
    
    table.insert(allNodes, node)
    return node
end

function Node.Print(self: INode)
    print(self.Value)
end

function Node.GetAllNodes(): {INode}
    return table.clone(allNodes)
end

return Node

When trying to perform a generalized iteration over Node.GetAllNodes() in another script...

--!strict
local Node = require(script.Parent.Node)

for i, generic in Node.GetAllNodes() do
	generic:Print()
end

...the following type error is emitted:

Type Error: (5,2) Type 'INode' could not be converted into 'INode'
caused by:
  Type 'Node' from 'game.Workspace.Node' could not be converted into 'Node' from 'game.Workspace.Node'
caused by:
  Property 'new' is not compatible.
Type
    '(a) -> Node'
could not be converted into
    '<T>(T) -> Node'; different number of generic type parameters

This issue can be worked around if I use pairs(Node.GetAllNodes()) or next, Node.GetAllNodes() instead. I've been observing this issue for as long as I've been using metatable types, though I never hammered down a direct simple repro until recently.

@MaximumADHD MaximumADHD added the bug Something isn't working label Feb 14, 2024
@MaximumADHD MaximumADHD changed the title Generic functions not being inferred correctly in generalized iteration? Generic functions not being typed correctly in generalized iteration? Feb 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Development

No branches or pull requests

1 participant