How to use Constructible that requires certain fields?

Hi I’m trying to use constructibles to instantiate a class in a callback. This constructible needs to have certain fields.

Here is an example of what I mean:

import haxe.Constraints;

// This is from an external library (deepnightlibs)
class ExternalClass<T:Recyclable> {
	public function new(valueConstructor:Void->T) {}
}

private typedef Recyclable = {
	function recycle():Void;
}

class Test {
	static function main() {
		testFunc(TestClass);
	}

	@:generic
	static function testFunc<T:Constructible<Void->Void>>(cls:Class<T>):T {
		// >> It errors here: "testFunc.T should be { recycle : () -> Void }" <<
		return new ExternalClass(() -> new T());
	}
}


class TestClass {
	public function new() {}

	public function recycle() {}
}


However there’s an issue, the callback requires that the constructible has certain fields (in this case recycle().

Pretty much ExternalClass requires a callback that returns a T:Recyclable. How would I do this with constructibles?

Here is the haxe playground of the above code and the error:

Managed to get a solution with a help of a certain chat ai program :nerd_face:

You can get a Constructible that requires certain fields by using intersections (the & operator):

testFunc<T:Constructible<Void->Void> & Recyclable>(cls:Class<T>)

Using the & to merge the two types Constructible & Recyclable.

Full example:

import haxe.Constraints;

typedef Recyclable = {
	function recycle():Void;
}

class Test {
	static function main() {
		testFunc(TestClass);
	}

	@:generic
	static function testFunc<T:Constructible<Void->Void> & Recyclable>(cls:Class<T>) {
		return new ExternalClass(() -> new T());
	}
}

class TestClass {
	public function new() {}

	public function recycle() {}
}

class ExternalClass<T:Recyclable> {
	public function new(valueConstructor:Void->T) {}
}

Here is a working example.