toType<T> function

T toType<T>(
  1. dynamic object
)

Global function that allow Convert an object to a specified type.

  • If the object is already of type T, it will be returned.

  • If the object is null, a ParsingException with a nullObject error will be thrown. If you want to ensure null safe values, consider using tryToType instead.

  • If the object cannot be converted to the specified type, a ParsingException will be thrown.

  • Supported conversion types:

Throws a ParsingException if it cannot be converted to the specified type.

Example usage:

final dynamicValue = '42';
final intValue = ConvertObject.toType<int>(dynamicValue); // 42

final dynamicValue2 = 'Hello';
final intValue2 = ConvertObject.toType<int>(dynamicValue2); // Throws ParsingException

final dynamicValue3 = null;
final intValue3 = ConvertObject.toType<int>(dynamicValue3); // Throws ParsingException with nullObject error

Implementation

T toType<T>(dynamic object) {
  if (object is T) return object;
  if (object == null) {
    throw ParsingException.nullObject(
      parsingInfo: 'toType',
      stackTrace: StackTrace.current,
    );
  }
  try {
    if (T == bool) return ConvertObject.toBool(object) as T;
    if (T == int) return ConvertObject.toInt(object) as T;
    if (T == double) return ConvertObject.toDouble(object) as T;
    if (T == num) return ConvertObject.toNum(object) as T;
    if (T == BigInt) return ConvertObject.toBigInt(object) as T;
    if (T == String) return ConvertObject.toString1(object) as T;
    if (T == DateTime) return ConvertObject.toDateTime(object) as T;
  } catch (e, s) {
    throw ParsingException(
      error: e,
      parsingInfo: 'toType',
      stackTrace: s,
    );
  }
  throw ParsingException(
    parsingInfo: 'toType',
    error:
        'Unsupported type detected. Please ensure that the type you are attempting to convert to is either a primitive type or a valid data type: $T.',
  );
}