luau
luau copied to clipboard
Type inference fails when using table function definition, forward-declared type, and typeof() types
This code snippet fails to infer the type of obj.f.
--!strict
local t = {}
function t.f(x: a) end
type a = any
local obj = t
print(obj.f) -- TypeError: Key 'f' not found in table 't'
obj is assumed to be of type typeof(t).
This makes obj.f an *error-type*, and it makes any values it returns an *error-type*, which makes any operations on its returned values an *error-type*, etc.
This snippet only fails in a few orderings of these statements. There are many changes that will make the error disappear, such as:
- defining the function inside the table.
--!strict
local t = {
f = function(x: a) end
}
type a = any
local obj = t
print(obj.f)
- defining the function without sugar syntax.
--!strict
local t = {}
t.f = function(x: a) end
type a = any
local obj = t
print(obj.f)
- defining the type above the function definition or using
a's type directly.
--!strict
local t = {}
type a = any
function t.f(x: a) end
local obj = t
print(obj.f)
--!strict
local t = {}
function t.f(x: any) end
local obj = t
print(obj.f)
- referencing
tdirectly instead ofobj.
--!strict
local t = {}
function t.f(x: a) end
type a = any
print(t.f)
- Casting
obj's type explicitly.
--!strict
local t = {}
function t.f(x: a) end
type a = any
local obj = t :: { f: (a) -> () }
print(obj.f)
This is fixed in the new solver.