Issues with type annotations

function Utilities:filter_by_class(instances: {Instance}, class: string): {Instance}
    for i, v in instances do
        if v.ClassName ~= class then
            table.remove(instances, i)
        end
    end

    return instances
end

The code above throws the error attempt to iterate over a Instance value. The goal of the function is to return a table filtered by ClassName given a table with values of type Instance, and a string denoting ClassName. How can I achieve this while avoiding this error?

try ipairs(instances) in the for loop

No dice, new error this time: invalid argument #1 to 'ipairs' (table expected, got Instance). The type checker seems to think my instances parameter isn’t a table?

Can you show me what values you send to the function?

local testUtil = Utilities:filter_by_class(game:GetService("TextChatService"):GetChildren(), "TextChatCommand")

Here you go, though I’m not sure it’s relevant. The error comes from the for loop, not the passed values.

try this

function Utilities:filter_by_class(instances: {Instance}, class: string): {Instance}
    if type(instances) == 'table' then
      for i, v in instances do
          if v.ClassName ~= class then
              table.remove(instances, i)
          end
      end
    else
      if v.ClassName ~= class then
          table.remove(instances, i)
      end
    end
    return instances
end

I appreciate your attempt to help, but this wont work. The issue lies in the type checker for some reason believing that the instances parameter is not a table, but rather a single Instance value.

Are you sure this is the problematic call? I could not reproduce the error with it.

The issue is not in the linter, which just warns about type related mismatches. It is that the function has not received a table, which :GetChildren() always returns, even an empty one.

Investigate where else the function is being called from and which arguments are passed. I would assume somewhere TextChatService is being sent instead of its children.

1 Like

It turns out I’m an idiot. To preface, I failed to mention that I’m using Knit in this project and the function in question is a Service.Client{} function. I simply forgot to add the player parameter to the function. :man_facepalming:

Can’t believe that took me so long. The help is much appreciated!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.