cosmology-tech / telescope

A TypeScript Transpiler for Cosmos Protobufs ⚛️
https://cosmology.zone/products/telescope
Apache License 2.0
146 stars 43 forks source link

return usable types from toJSON #605

Closed turadg closed 4 months ago

turadg commented 5 months ago

The toJSON method on the generated classes returns a transformation of the data that can be JSON-encoded. E.g. UInt8Array becomes a Base64 string.

Currently those methods return unknown but they could return an actual type by wrapping existing interfaces in a utility types.

Consider,

export interface Duration {
  seconds: bigint;
}

The Duration class's toJSON could return that instead of unknown as it does now:

export const Duration = {
  typeUrl: '/google.protobuf.Duration',

  toJSON(message: Duration): JsonSafe<Duration> {
    const obj: any = {};
    message.seconds !== undefined &&
      (obj.seconds = (message.seconds || BigInt(0)).toString());
    message.nanos !== undefined && (obj.nanos = Math.round(message.nanos));
    return obj;
  },
}

A case with UInt8Array:

export interface RequestQuery {
  data: Uint8Array;
  path: string;
  height: bigint;
  prove: boolean;
}

An example of a utility that would handle both:

type JsonSafe<T> = {
  [Prop in keyof T]: T[Prop] extends Uint8Array ? string : T[Prop] extends bigint ? string : T[Prop];
}

(playground link)

pyramation commented 4 months ago

should be good to go!

https://github.com/cosmology-tech/telescope/pull/620

should be able to publish after confirmation