I was working on a project and encountered an issue with the type checking.
This is approximately what my code looks like if I generalized the problem.
--!strict
local function doSomething(number: number)
end
local variable: number? = 5
if not variable then
variable = 3
doSomething(variable)
end
If I hover over ‘variable’ in the line where I call the function, it shows: "Type ‘nil’ could not be converted into ‘number’. I have very clearly set ‘variable’ to 3 which is a number and not nil. Is this an error or am I just missing something?
You told the type inference engine that variable MIGHT be a number, not that it will be a number. It prioritizes that the condition fed it (in this case, your variable HAS to be nil), no matter if you changed the variable in function or not.
This is usually why I avoid uncertainty or just don’t use strict
--Gives type error
local variable: number? = 5
--Fixed by just removing the uncertainty
local variable: number = 5
--Or by overriding with a new variable in the lower scope
if not variable then
variable = 3
local numbervariable = 3
doSomething(numbervariable)
end
Another unrelated problem; is that using if not variable doesn’t actually guarantee it will be a number.
This is more obvious if you write out it’s other form
if variable == nil then
If you want to be absolutely certain, use manual type checks
local function VariableTypeCheck(ExpectedType: string, Variable: any?)
return typeof(Variable) == ExpectedType
end
if not VariableTypeCheck("number", variable) then
end
I was thinking of using the workaround you showed me, but it feels like unnecessary code just to a avoid an issue that shouldn’t really exist. I feel like this should not happen to begin with as I clearly set the variable to a number after checking if it isn’t. Do you think I should make a feature request / bug report on this?
This happens to me a lot in more of my larger main scripts where I clearly define a variable. It is indeed quite annoying to see massive orange underlines when trying to do something.