Type Notation for Objects

How can type notation be done for objects within OOP?

I have a class and its interface declared with:

type ExampleClassInterface = {
	new : (name: string, value: number) -> Object	
}

local ExampleClass : ExampleClassInterface = {}

and the object type with:

export type Object = {
	Get : (number),
	Set : () -> number
}

This works fine for object properties and methods with dot notation, but breaks the intellisense as soon as I use object methods using colon notation such as:

function ExampleClass:Set(value)
	self.Value = value
end

Is there a way to create a type interface with colon notation?

1 Like
local MyClass = {}
MyClass.__index = MyClass

-- define the class type
-- typechecking will detect methods from the class
export type ClassType = typeof(setmetatable({} :: {
	-- define properties of the class objects here
	Value: number,
}, MyClass))

function MyClass.new(num: number): ClassType -- define return type for typechecking object
	local self = setmetatable({}, MyClass) :: ClassType -- allows typechecking in constructor
	
	self.Value = num
	
	return self
end

-- manually define the self argument for typechecking
-- this function is still called with the colon operator
function MyClass.GetValue(self: ClassType): number
	return self.Value
end

return MyClass
local obj = MyClass.new(10)
local value = obj:GetValue()
print(value) -- 10
1 Like

Would this work similarly to how self is used as the first argument for method definitions in Python, while the self parameter is not used for calls?

1 Like

A simple self: Object

export type Object = {
	Get: (self: Object, number) -> (),
	Set: (self: Object) -> number
}

It could really have any name, self will always be the first parameter when a function is called as a method (Table:Function())

1 Like