Luau Typechecking: Requesting a table has one minimum named index, but can have more

I created my own lightweight version of Maid, and I’m currently trying to set type checking types for functions.

One of my functions, Maid.Add, can take either an RBXScriptConnection, Instance, or a table - as long as it has a function under it named Destroy.

The problem here is I can’t figure out what sort of syntax I need to use for allowing extra members in the table. It’s only working if the table has Destroy, and that’s it.

function Maid:Add(Task: RBXScriptConnection|Instance|{Destroy: (...any?) -> (...any?)})
	table.insert(self._tasks, Task)
	
	return Task
end

As you can see in the image below, the bottom table warns when it ideally shouldn’t be warning. “none of the union types are compatible”.

image

I was looking through the typechecking docs for Luau and didn’t have any luck. The closest thing I could find are “generics”. Would be nice if I could be pointed into the right direction with this as it’s all still quite new to me, thank you!

1 Like

Try

Task: {Destroy: (...any?) -> (...any?), [any]: any}

This means that it must at least have the function Destroy but may have any other instance variables within the closure. But if it only has one function, why not make it accept a function instead?

1 Like

This seems to be a solution as it’s not warning anymore, thank you so much!

The reason why is because it supports custom data types that need to be garbage collected with their own Destroy function, such as a GoodSignal class with an alias for DisconnectAll being “Destroy” so it’ll disconnect all connections associated with that Signal, so these will be able to have any other type associated with the same table.

1 Like