luau icon indicating copy to clipboard operation
luau copied to clipboard

Type inference fails when using table function definition, forward-declared type, and typeof() types

Open goldenstein64 opened this issue 3 years ago • 1 comments

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 t directly instead of obj.
--!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)

goldenstein64 avatar Dec 04 '22 21:12 goldenstein64

This is fixed in the new solver.

andyfriesen avatar Apr 04 '23 22:04 andyfriesen