COMMUNITY

How to check generic type inside parametrised function

Hi all! I’m trying to implement basic validation for dynamic data structures (those are coming from parsed JSON).

I want to have something like the following:

  public static function getField<T>(
      obj: Dynamic,
      fieldName: String,
      dflt: Null<T>,
      context: Context): Null<T> {
    var val = Reflect.field(obj, fieldName);
    if (val == null) {
      return dflt;
    }
    if (!Std.is(val, T)) {
      throw new ValidationError('Unexpected value for ${context.getEntityInfo()}');
    }
    return val;
  }

but Std.is(val, T) is not working, because T is compilation type…

Can I achieve the same by some other means?

You can try to add @:generic to specialize your function per type:

@:generic
public static function getField<T>( ...

This will generate more code though.

Alternatively you could use a json library that can do more validation, or output typed data, like json2object.

I’ve tried to add @:generic before public static function getField<T>( but still get the same error Type parameter T is only available at compilation and is not a runtime value on Std.is(val, T) check.