How to typecheck module.new in a class

Hi,

I am new to typechecking and I think i’ve got the basics of it but I am having a problem where I don’t know how to type check Module.new().

I’ve seen someone use something like


type self = {
	_sword: Tool,
	_animations: Folder,
	_settings: tab,
	_connections.ClassType, -- they use classtype but how?
	_hitbox.ClassType, 
}

Here’s the full code

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

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Source = ReplicatedStorage.Source

local RaycastHitbox = require(Source.RaycastHitboxV4)
local Trove = require(Source.Packages.Trove)

type tab = { 
	_damage: number,
	_yield: number,
	_attacktime: number,
}

type self = {
	_sword: Tool,
	_animations: Folder,
	_settings: tab,
	_connections, -- need help with this
	_hitbox, -- need help with this
}

export type Sword = typeof(
	setmetatable({} :: self, Sword)
)

function Sword.new(sword: Tool, setting: tab): Sword
	local self = setmetatable({} :: self, Sword)
	
	self._sword = sword
	self._animations = sword:FindFirstChild("Animations"):: Folder
	self._settings = setting
	self._connections = Trove.new()
	self._hitbox = RaycastHitbox.new(self._sword:FindFirstChild("Handle"))
	
	return self
end

-- methods

function Sword:Equip()
	print("Equipped")
end

function Sword:Unequip()
	print("Unequipped")
end

function Sword:Destroy()
	self._connections:Destroy()
end

return Sword

I tried adding export ClassType to trove and it still didn’t work

export type ClassType = typeof(setmetatable({} :: {
	_objects: { RBXScriptConnection },
	_cleaning: boolean
}, Trove))
2 Likes
  1. In the Trove module, ensure you’re exporting the type:
-- This is inside the Trove module
export type ClassType = typeof(setmetatable({} :: {
	_objects: { RBXScriptConnection },
	_cleaning: boolean
}, Trove))
  1. In the main module where you wish to use this type, first require the Trove module:
local Trove = require(Source.Packages.Trove)
  1. Then, use the imported ClassType type from Trove for the _connections field of the self type:
type self = {
	_sword: Tool,
	_animations: Folder,
	_settings: tab,
	_connections: Trove.ClassType, -- this is how you reference the type
	_hitbox: RaycastHitbox.ClassType, -- assuming RaycastHitbox has an exported ClassType as well
}

In the above, Trove.ClassType references the exported ClassType type from the Trove module.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.