Confusion with my codes typechecking

Hello, I was recently trying to figure out how to utilize luau’s type checking. I find it quite confusing though.

In my code it states on line 15 and line 24 that:
Unknown type used in + operation; consider adding a type annotation to 'self',
Unknown type used in - operation; consider adding a type annotation to 'self'
How exactly do I specify self’s type in this code?

I am not sure on how to specify what AccountClass’s new method returns either.

--!strict
local AccountClass = {}
AccountClass.__index = AccountClass

function AccountClass.new(Name: string, Balance: number)
	local self = {}
	self.Name = Name
	self.Balance = Balance
	
	return setmetatable(self, AccountClass)
end

function AccountClass:Deposit(Credit: number)
	if Credit > 0 then
		self.Balance += Credit
	else
		warn(string.format("Could not deposit %f credit to %s's account as it is less then zero.", Credit, self.Name))
	end
end

function AccountClass:Withdraw(Debit: number)
	if Debit > 0 then
		warn(string.format("Could not withdraw %f debit from %s's account as it is more then zero.", Debit, self.Name))
	else
		self.Balance -= Debit
	end
end

local Account = AccountClass.new("John Doe", 500.00)
Account:Deposit(200)
print(Account.Balance)

Try something like:

type Account = typeof(AccountClass.new())

Then in your functions do something like:

function AccountClass:Deposit(credit: number)
    self = self :: Account
    if credit > 0 then
        self.Balance += credit
    end
end

Or if you want a shorthand option you could do something like:

function Account:Deposit()
    self = self :: typeof(AccountClass.new())
end

Basically, in type annotation, typeof returns the type of the argument that is passed if that makes sense.

There’s also the option to define it like so:

function Account.Deposit(self: Account --[[or typeof(Account.new())]], amount)
3 Likes

Thanks, seemed to work, I have concluded that I hate typechecking.

1 Like