Typechecker in strict mode can't narrow down Type? to Type despite reassignment from nil

--!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?


PS: I don’t have the new luau type solver on, I cannot tell you if that would fix it since I get an enormous memory leak with it enabled due to this bug

This is not a bug because you hard coded the type to be of number so the type checker will not override this.

local Part: Part? = nil
Part = game.Players.Player

--Type of part will remain that of a part despite setting the variable to a player type

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
1 Like

Thanks for the report!

The new type solver does handle this case correctly.

Cheers!

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