Referencing A Sub-Type

I’m making a component system using classes and type-checking. Each component will be it’s own class and it will export it’s own type. I’d want to be able to use the food type without having to require the food component module, only the main component module.

Components.lua

local FoodComponent = require(script.Parent.FoodComponent)

export type Component = {
	Food: FoodComponent.Food?,
}

return {
	["FoodComponent"] = FoodComponent
}

FoodComponent.lua

-- Authorized Use By Dissonant Realms and Galicate
-- Programmer : Galicate @ 7/16/2024 4:37 PM

local FoodComponent = {}

export type Food = {
	Nutrition: number,
	Saturation: number,
	CanAlwaysEat: boolean?,
	ConsumeTime: number?,
	Effects: {}?
}

function FoodComponent.new(nutrition: number?, saturation: number, canAlwaysEat: boolean?, consumeTime: number?, effects: {}?)
	local self = setmetatable({}, FoodComponent)
	
	self.Nutrition = nutrition
	self.Saturation = saturation
	self.CanAlwaysEat = canAlwaysEat or false
	self.ConsumeTime = consumeTime or 1.6
	self.Effects = {}
	
	return self
end

function FoodComponent:GetNutrition(): number
	return self.Nutrition
end

function FoodComponent:GetSaturation(): number
	return self.Saturation
end

function FoodComponent:IsAlwaysEdible(): number
	return self.CanAlwaysEat
end

function FoodComponent:GetConsumeTime(): number
	return self.ConsumeTime
end

function FoodComponent:GetStatusEffects()
	return self.Effects
end

FoodComponent.__index = FoodComponent
return FoodComponent
1 Like

You would have to re-export your subtypes in your main components module.

I was afraid of that, is there any way to do that without just copying and pasting it in? I’d like to keep each component as separate as possible.

You don’t have to copy paste the entire thing, you would just have to do

export type Food = FoodComponent.Food

Unfortunately, you can only get types from modules that you are directly requiring. It is the main downsides of the package manager wally for me - you would have to use something like wally-package-types to automatically re-export types to reference them.

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