encodeTyped<T> function

dynamic encodeTyped<T>(
  1. T value, {
  2. TransferCodec<T>? codec,
})

Encodes a typed value to its transfer representation. (JSON)

codec can be used to override the default codec for type T. name is used in error messages for debugging purposes.

Implementation

dynamic encodeTyped<T>(T value, {TransferCodec<T>? codec}) {
  if (value == null) {
    if (!TypeCheck<T>().isNullable) {
      // this should not be possible
      throw CodecException.typeMismatch(T, value.runtimeType, null);
    }

    return null;
  }

  codec ??= TransferCodec.find<T>();
  if (codec != null) {
    return (codec as dynamic).encode(value);
  }

  throw ApiError.invalidType(T);
}