MemeLabs / strims

GNU Affero General Public License v3.0
10 stars 6 forks source link

reimplement ts oneofs #82

Closed slugalisk closed 3 years ago

slugalisk commented 3 years ago

implement onofs as an immutable class typed as a discriminated union.

export type IInvitationOneOf =
  | { invitationB64: string }
  | { invitationBytes: Uint8Array };

export type TInvitationOneOf = Readonly<
  { case: 0 } | 
  { case: 1; invitationB64: string } | 
  { case: 2; invitationBytes: Uint8Array }
>;

class InvitationOneOfImpl {
  invitationB64: string;
  invitationBytes: Uint8Array;
  case: InvitationCase = 0;

  constructor(v?: IInvitationOneOf) {
    if (v && "invitationB64" in v) {
      this.case = 1;
      this.invitationB64 = v.invitationB64;
    }
    if (v && "invitationBytes" in v) {
      this.case = 2;
      this.invitationBytes = v.invitationBytes;
    }
  }
}

export const InvitationOneOf = InvitationOneOfImpl as {
  new (): Readonly<{ case: 0 }>;
  new <T extends IInvitationOneOf>(v: T): Readonly<
    T extends { invitationB64: string } ? { case: 1; invitationB64: string } :
    T extends { invitationBytes: Uint8Array } ? { case: 2; invitationBytes: Uint8Array } :
    never
  >;
};

export enum InvitationCase {
  NOT_SET = 0,
  INVITATION_B64 = 1,
  INVITATION_BYTES = 2,
}

update the decoder ex.

m.invitation = new CreateNetworkFromInvitationRequest.InvitationOneOf({ invitationB64: r.string() });