We often write classes in Luau, but since types came out, it became difficult to get type checking right without complex workarounds. Today, I wanted to share one of the class method writing methods that I started using recently.
--!strict
type Impl = {
__index: Impl,
new: (name: string, balance: number) -> Account,
deposit: (self: Account, credit: number) -> (),
withdraw: (self: Account, debit: number) -> (),
}
type Proto = {
name: string,
balance: number
}
local Account: Impl = {} :: Impl
Account.__index = Account
export type Account = typeof(setmetatable({} :: Proto, {} :: Impl))
function Account.new(name: string, balance: number)
local self = setmetatable({} :: Proto, Account)
self.name = name
self.balance = balance
return self
end
function Account:withdraw(debit): ()
self.balance -= debit
end
function Account:deposit(credit): ()
self.balance += credit
end
return Account
If you donât like so many types inside your class module, you can put them in a separate module, eg. local Types = require(script.Types)
.