Is this expected behaviour ? - Generic static class fields

trying out some edge cases with generics in static fields, I came over this Try Haxe!

import Type;

class Foo<T> {
	static public var first: T;
  static var isSet: Bool = false;
  var val: T;
  public function new(v: T) {
    val = v;
    if ( ! isSet) {
			first = v;
      isSet = true;
  public function getFirst(): T {
		return first;

class Test {
  static function getName(vt: ValueType) {
    return switch vt {
			case TNull: "Null";
			case TInt: "Int";
			case TFloat: "Float";
			case TBool: "Bool";
			case TObject: "Object";
			case TFunction: "Function";
			case TClass(c): Type.getClassName(c);
			case TEnum(e): Type.getEnumName(e);
			case TUnknown: "unknown";
  static function test<T>(v: T, vt: ValueType) {
    final name = getName(vt);
    if (Type.typeof(v) == vt) 
      trace('value is $name with value $v');
      trace('oops value $v is not a $name');
  static function main() {
    trace("Haxe is great!");
    var f1 = new Foo(1);
    var e1 = f1.getFirst();
    test(e1, TInt);
    var f2 = new Foo("Bar");
    var e2: String = f2.getFirst();                           // get an Int but expect a String. Why does this compile ???
    test(e2, TClass(Type.resolveClass("String"))); // I am expecting a String but get an Int

I am not using Dynamic but still can get the wrong type for e2 in this example. For me it is a bug.
My goal is not getting this to run, but to have a defined behaviour in my Haxe to nim target which am working on again - and I am having a hard time with generics in static fields :slight_smile:

Cheers Adrian.

Try compiling with nightlies, you’ll see the actual error (spoiler alert: can’t use T from Foo<T> in its static fields)

1 Like

Does this mean, that static fields can’t be generic ? which would be reasonable - and a headache less in implementing this in nim

Currently not. We might actually implement a solution for this when @:generic is involved, but it can’t work without that. See [] Type Parameters (Type System) · Issue #139 · HaxeFoundation/ · GitHub for last discussion on the topic