Help with custom Instance.new() like type checking

I made a function in module that acts similiar like Instance.new() but i have problem with type-checking. The function takes String to check what type of Force should it return and returns according Force class with it’s properties.
I don’t really know how do i typecheck it. I tried doing:

type NewForce:("Repel")->{Type:"Repel", Position:Vector3, Range:number, Power:number} | ("RepelConstant")->{Type:"RepelRepelConstant", Position:Vector3, Range:number, Power:number} | ("Turbulence")->{Type:"Turbulence", Position:Vector3, Scale:number, Power:number}

But when i try to make a NewForce with the script, here is what shows up:


Here is the script in module that returns the class:

function module.NewForce(Type)
	if Type == module.TypeForce.Repel then
		return {["Type"] = Type, ["Position"] = Vector3.zero, ["Range"] = 12, ["Power"] = 15}
	end
	if Type == module.TypeForce.RepelConstant then
		return {["Type"] = Type, ["Position"] = Vector3.zero, ["Range"] = math.huge, ["Power"] = 15}
	end
	if Type == module.TypeForce.Turbulence then
		return {["Type"] = Type, ["Position"] = Vector3.zero, ["Power"] = 15, ["Scale"] = 0.25}
	end
end

The NewForce type is actually a part on moduleType type. I made NewForce as a standalone type to make it easier to read. Here is how it actually looks like:

type moduleType = {
	NewForce:("Repel")->{Type:"Repel", Position:Vector3, Range:number, Power:number} | ("RepelConstant")->{Type:"RepelRepelConstant", Position:Vector3, Range:number, Power:number} | ("Turbulence")->{Type:"Turbulence", Position:Vector3, Scale:number, Power:number},
	new:()->Emitter
}
3 Likes

Have you tried doing something like this:

type NewForceArguments = "Repel" | "RepelConstant"
type GenericForceType<T> = {Type: T, Position: Vector3, Power: number}
type NewForce = (forceType: NewForceArguments) -> (GenericForceType<forceType> & {Range: number}) | (forceType: "Turbulence") -> (GenericForceType<forceType> & {Scale: number})

At the moment, I cannot verify if this will work

2 Likes