Auto Type Checking

I present to you, my way of auto type checking classes created with your standard OOP structure. Not sure if this is good practice, but I discovered it trying to be as lazy as possible, I couldn’t find any post about doing it this way but yea here it is.

local Class = {}
Class.__index = Class

function Class.new(): Class_Type

	local self = {}

	

	return setmetatable(self, Class) :: typeof(self) & typeof(Class)

end

function Class:Test()

	self = self :: Class_Type

	

end

export type Class_Type = typeof(Class.new())

return Class

Essentially you have your standard setup except you have the export type at the bottom, which is a but unusual, but it’s needed to make it work.

But now whenever you add a variable into the self table defined in the “.new” function, the other functions will recognize it and add it to the type allowing for super easy autofill with the least amount of effort possible.

4 Likes

you could also do:

type Class = typeof(Class.new(...))

to make it fill in the parameters of the constructor (therefore truly automatic)

for methods i just do:

function Class.Test(self: Class)

end

Autocomplete and intellisense works just fine, though roblox’s autocomplete might suggest Class.Test instead of Class:Test when you do Class.

2 Likes

I see I see, fair enough, I personally have gotten used to writing the colon instead of the period, but I’ll try it out and see how I feel about it. :+1:

1 Like

hello . Is it me or roblox autocomplete nolonger supports autocomplete for classes?

eg)

local module = {}
module.__index = module

function module.new()
     local self = setmetatable({},module)
     self.Foo = "Foo"
     self:init()
     return self
end)

function module:init()
     --foo is not recgonise in self
end)

return module

thank you in advance :smiley:

foo is recognized in self in that case, but I think it only is if it’s called inside of the .new function,

when adding a new function and going to type in there, the problem then arises with things not auto filling. :confused:

1 Like