Typechecking problem

Hi, I want to create a class that has an attribute which is a table containing objects of another class (which I called NestedClass), indexed by a string. I’m pretty new to type checking am I doing something wrong here?

– MyClass

--!strict

local nestedClass = require(script.NestedClass)
type nestedType = nestedClass.NestedClassType

local MyClass = {}
MyClass.__index = MyClass

function MyClass.new()
	local self = setmetatable({}, MyClass)
	self.nestedObjects = {} :: {[string] : nestedType}
	return self
end


function MyClass:setNestedObjectA(key : string, a:string) : ()
	if not self.nestedObjects[key] then
		self.nestedObjects[key] = nestedClass.new(a)
	else
		return self.nestedObjects[key]:SetA(a)
	end
end



return MyClass

– Nested Class

--!strict

local NestedClass = {}
NestedClass.__index = NestedClass

function NestedClass.new(a: string)
	local self = setmetatable({}, NestedClass)
	self.a = a
	return self
end

function NestedClass:SetA(a:string): ()
	self.a = a
end


export type NestedClassType = 
	typeof(NestedClass)
	


return NestedClass

It gives me an error on line 20 of MyClass

you just need to fix up your types

this type here isn’t correct since it doesn’t consider that NestedClass is using metatables

export type NestedClassType = typeof(NestedClass)

so it should be

type NestedClassData = { a: string }
export type NestedClassType = typeof(NestedClassData, NestedClass))

-- or if you're using the new type solver
export type NestedClassType = setmetatable<NestedClassData , typeof(NestedClass)>

do the same with MyClass and set the return type of the .new functions to their respective class type

another important thing is when you’re setting a method to use :, you can’t set self to have the correct type nicely so what you can do is define it as a method like this

function MyClass.setNestedObjectA(self: MyClassType, key : string, a:string) : ()

in the above code, you have self correctly typed and you can still call it as MyClass:setNestedObjectA()

everything I just showed, you can refer to Luau documentation for more info:

1 Like