tryToType<T> function

T? tryToType<T>(
  1. dynamic object
)

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

If the object is already of type T, it will be returned. If the object is null, a null value will be returned. If you want to ensure non-nullable values, consider using toType instead. If the object cannot be converted to the specified type, a ParsingException will be thrown.

Supported conversion types:

Example usage:

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

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

Implementation

T? tryToType<T>(dynamic object) {
  if (object is T) return object;
  if (object == null) return null;
  try {
    if (T == bool) return ConvertObject.tryToBool(object) as T?;
    if (T == int) return ConvertObject.tryToInt(object) as T?;
    if (T == BigInt) return ConvertObject.tryToBigInt(object) as T?;
    if (T == double) return ConvertObject.tryToDouble(object) as T?;
    if (T == num) return ConvertObject.tryToNum(object) as T?;
    if (T == String) return ConvertObject.tryToString(object) as T?;
    if (T == DateTime) return ConvertObject.tryToDateTime(object) as T?;
  } catch (e, s) {
    throw ParsingException(
      error: e,
      parsingInfo: 'tryToType',
      stackTrace: s,
    );
  }
  throw ParsingException(
    error: 'Unsupported type: $T',
    parsingInfo: 'tryToType',
  );
}