Cannot fix type error

Hello developers,

I’m coding my own Signal module, and I’m in trouble.

If I try to use the module, it says “Type ‘Signal’ could not be converted into '{ _Connections: {{ Disconnect: () → (), _callback: (…any) → () }} }”.

Here is my module:

-- Signal.lua
--!strict
local Signal = {}

Signal.__index = Signal

type Connection = {
	Disconnect: () -> ()
}

type Signal = typeof(setmetatable({}, Signal))

function Signal.New(): Signal
	return setmetatable({
		_Connections = {}
	}, Signal)
end

function Signal:Destroy(): ()
	setmetatable(self, nil)
	self._Connections = nil
end

function Signal:Connect(callback: (...any) -> ()): Connection
	local Connection = {}
	Connection._callback = callback
	Connection.Disconnect = function()
		for index, value in ipairs(self._Connections) do
			if value == Connection then
				self._Connections[index] = nil
				break
			end
		end
	end
	table.insert(self._Connections, Connection)
	return Connection
end

function Signal:Once(callback: (...any) -> ()): Connection
	local Connection: Connection
	local HasFired: boolean = false
	Connection = self:Connect(function(...: any)
		if not HasFired then
			HasFired = true
			Connection.Disconnect()
			task.defer(callback, ...)
		end
	end)
	return Connection
end

function Signal:Wait(): ...any
	local CurrentThread = coroutine.running()
	self:Once(function(...: any)
		coroutine.resume(CurrentThread, ...)
	end)
	return coroutine.yield()
end

function Signal:Fire(...): ()
	for _, Connection in ipairs(self._Connections) do
		local callback: () -> () = Connection._callback
		if callback then
			task.defer(callback, ...)
		end
	end
end

return Signal
2 Likes

Assuming the type error occurs within the Signal.New() function, a typecast using the :: operator on the return value may work:

function Signal.New(): Signal
	return setmetatable({
		_Connections = {}
	}, Signal) :: Signal
end

Alternatively, removing the --!strict typechecking mode will get rid of the error (it will use --!nonstrict by default), while still keeping autocomplete functionality.

That seems not working, and I don’t want to use ‘--!nonstrict’. Is there any other way?

If you don’t want to be bothered by it you can just typecast it ‘:: any’

Oh yeah, that actually fixed the issue. Thank you for replying!

1 Like

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