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 (!, T)) {
      throw new ValidationError('Unexpected value for ${context.getEntityInfo()}');
    return val;

but, 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:

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, T) check.