Issue with strictmode type errors

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.

Could someone help me?


1 Like

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()).

I would also suggest just using RBXScriptSignal:Once in your case.

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.

3 Likes

Based on the screenshots, would it not be better to make it a :Once connection? Or is the variable being used elsewhere?

1 Like

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:

Just do local rbxcon: RBXScriptConnection?

He has a point.
You want to disconnect it after first trigger so there really no point of having any of that.
Just use :Once.

The RBXConnection disconnects only when a certain parameter is met (not shown in my exemple), that’s why i’m not using :Once()

Silencing by typecasting any fixed the issue, thank you for that as well as explaining all the cases to me! You’ve provided great help.

Also thank you to all the other people who tried helping out with this.

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