--!strict
local num: number? = nil
num = 2 -- num will definitely not be nil now
for i = 1, num do -- Type Error: Type 'number?' could not be converted into 'number'
end
Expected behavior
num to be inferred as number when it was reassigned, not number?
I’m not good at explaining things so ill try explaining better. If you explicitly declare a type, then the type checker assumes that variable will always hold that type forever until you redefine it. If you want it to change then let the engine infer it (not always accurate)
Edit: i was thinking about something else but yea this is an issue with the type checker. Commonly happens only with normal data types like tables, strings, number, and others
Luau’s new solver does have control-flow analysis, it’s just very primitive and can only refine basic stuff like conditionals with discriminate unions.
type Foo = {
Tag: "Foo",
Value: number
}
type Bar = {
Tag: "Bar",
Value: string
}
local function Baz(Input: Foo | Bar)
if Input.Tag == "Foo" then
-- okay
return Input.Value + 2
end
-- bad
return Input.Value + 1
end