luau icon indicating copy to clipboard operation
luau copied to clipboard

[New Solver] "Value of type 'unknown' could be nil" errors

Open NirlekaPlay opened this issue 5 months ago • 1 comments

I always encounter the confusing type error whenever I use a function directly on an if statement. This is the simplest reproduction I can make:

--!strict

local ExpireableValue = {}
ExpireableValue.__index = ExpireableValue

export type ExpireableValue = typeof(setmetatable({} :: {
}, ExpireableValue))

function ExpireableValue.canExpire(self: ExpireableValue): boolean
	return true
end

function ExpireableValue.update(self: ExpireableValue): ()
	if self:canExpire() then -- TypeError: Value of type 'unknown' could be nil
		return
	end
end

return ExpireableValue

However, if I assign the returned value of the function to a variable and use that variable in the if statement:

function ExpireableValue.update(self: ExpireableValue): ()
	local canExpire = self:canExpire()
	if canExpire then
		return
	end
end

The error is gone. Strangely enough, if I don't use the variable and use the function directly on the if statement anyway, the typechecker doesn't complain either:

function ExpireableValue.update(self: ExpireableValue): ()
	local canExpire = self:canExpire()
	if self:canExpire() then
		return
	end
end

The expected behaviour should be that the typechecker knows that calling self:canExpire() returns a value of type boolean, without assigning it to a variable first, which sometimes can be undesirable.

NirlekaPlay avatar Jul 21 '25 16:07 NirlekaPlay

See https://github.com/luau-lang/luau/issues/1868, although it is mentioned that it is fixed, but it might still be stuck behind a FFlag

JohnnyMorganz avatar Jul 21 '25 17:07 JohnnyMorganz