Get the type of a function passed to :Connect()

I have some functions defined such that they take in an argument that eventually gets passed in to GuiButton.Activated:Connect() or other similar events.

Can I have Studio type-check these (usually anonymous) functions’ parameters? Something like

local function example(text: string, activated: ???)
	local self = Instance.new("TextButton")
	self.Text = text
	self.Activated:Connect(activated)

	return self
end

I would just write the exact types (inputObject: InputObject, clickCount: number) -> () for the function, but there are other times where I use this pattern for different events and I don’t want to have duplicate built-in Roblox types.

I’ve tried something with

type Activated = typeof(Instance.new("ImageButton").Activated.Connect)

but that’s just Activated(self: RBXScriptSignal, func: (inputObject: InputObject, clickCount: number) -> ()): RBXScriptConnection. I need the type of Activated’s func parameter. index<Activated, "func"> doesn’t work here, presumably because it’s not a table.

If you mean you want to type activated exactly as it is for SomeInstance.Activated without typing it yourself, you can take advantage of type inference, where intellisense interprets the type for you.

So, instead of:

local function example(text: string, activated: someType)

Do:

local function example(text: string, activated) --> "activated" will be interpreted as whatever type is required for self.Activated:Connect

Alright, that seems to work. I think the reason I had so much difficulty with this is that I wanted to have it as an optional and was trying to tack on | false? to all the types I could make.

My VSCode Roblox LSP also can’t figure out this type, so that may have thrown me off.

I was originally doing

if action then
	self.Activated:Connect(function(...)
		action(self, ...)
	end)
end

but this seems too complex for the typechecker.

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