Hey, i’ve recently been getting into using strictmode more often and have recently found myself confused when using it with RBXconnections.
In the following code, i am trying to disconnect an RBXConnection as i no longer need it, but it won’t let me set the connection to nil without warning me. I’ve tried multiple ways to go around it but have failed each time.
You can typecast :: any to silence the type error when setting rbxcon to nil (rbxcon = nil :: any) in the first image, in the second image typecast rbxcon to RBXScriptConnection to manually refine it ((rbxcon :: RBXScriptConnection):Disconnect()).
The first error is being thrown because in the first image rbxcon can only be an RBXScriptConnection, and nil isn’t RBXScriptConnection.
In the second image, the type of rbxcon is now optional (rbxcon: RBXScriptConnection?), but as the type has not been refined down to just RBXScriptConnection, calling :Disconnect() raises a type error, as the type checker thinks it could be nil.
Setting rbxcon to nil raises a type error because by setting the variable type to RBXScriptConnection you are stating that it will always be that, it doesn’t expect a nil value.
RBXScriptConnection? would account for a nil value (you’ll need to have the script check that the variable isn’t nil through an IF before using any of the type’s methods to appease the type checker, since nil doesn’t have those methods [spoiler]or just typecast[/spoiler])…
local newConnection: RBXScriptConnection?
...
-- Ensures that newConnection is not nil at this time. This affirms that the variable is an RBXScriptConnection, silencing the type solver without using type casting. Works on both current and beta type solvers.
if not newConnection then
return
end
newConnection:Disconnect()
newConnection = nil
…but you shouldn’t be bothering with that because: