Having trouble with inheritance and OOP

By the way, autocomplete gets confused with metatable chaining at the moment, so you can get autocomplete back by creating a union type that is a theoretical metatable that includes properties in the table, and methods in the metatable, and then whichever class it inherits.

It also might be a good idea to call CreateTool.new() for your object to inherit properties as well.

Final result looks like:
image

Pickaxe:

local CreateTool = require(script.Parent.Tool)

local Pickaxe = {}
setmetatable(Pickaxe, CreateTool)
Pickaxe.__index = Pickaxe

function Pickaxe.new(owner, durability, damage)
	local NewPickaxe = CreateTool.new(owner, durability, damage)
	setmetatable(NewPickaxe, Pickaxe)

	return NewPickaxe :: Pickaxe
end

function Pickaxe:CreatePart()
	print(3)
end

function Pickaxe:TestPart()
	print(4)
end

export type Pickaxe = typeof(setmetatable({} :: {
	-- list properties that aren't in Tool here
	
}, {} :: { __index: {
	-- list methods here (class methods called with a colon have self passed implicitly, in this case it would be the Pickaxe type)
	CreatePart: (self: Pickaxe) -> ();
	TestPart: (self: Pickaxe) -> ();
}})) & CreateTool.Tool

return Pickaxe

Tool:

local Tool = {}
Tool.__index = Tool

function Tool.new(owner, durability, damage)
	local NewTool = {}
	setmetatable(NewTool, Tool)

	NewTool.Owner = owner
	NewTool.Durabiltiy = durability
	NewTool.Damage = damage


	return NewTool
end

function Tool:UseTool()
	print(5)
end

function Tool:ChangeValue(val)
	self.Owner = val
	print(self.Owner)
end

export type Tool = typeof(Tool.new(Instance.new('Player'), 1, 1)) -- this will inherit Tool methods as well as properties

return Tool

Then suppose we have a third even less primitive class (let’s say DiamondPickaxe), you could implement its class and type like so:

local Pick = require(script.Parent.Pick)

local DiamondPick = {}
DiamondPick.__index = DiamondPick

setmetatable(DiamondPick, Pick)

function DiamondPick.new(...)
	local newDiamondPick = Pick.new(...)
	setmetatable(newDiamondPick, DiamondPick)
	newDiamondPick.Durable = math.random(0, 1) == 1
	
	return newDiamondPick :: DiamondPick
end

function DiamondPick:IsDurable()
	return self.Durable --> true or false depending on whether or not it's durable
end

export type DiamondPick = typeof(setmetatable({} :: {
	-- list properties that aren't in Pickaxe here
	Durable: boolean
}, {} :: { __index: {
	-- list methods here (class methods called with a colon have self passed implicitly, in this case it would be the Pickaxe type)
	IsDurable: (self: DiamondPick) -> boolean;
}})) & Pick.Pickaxe

return DiamondPick

image

2 Likes

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