kklas / anchor-client-gen

A tool for generating solana web3 clients from anchor IDLs.
MIT License
135 stars 21 forks source link

`kind` of typescript union members should be static #37

Closed JoeHowarth closed 2 years ago

JoeHowarth commented 2 years ago

I'd like to branch on variant kind like below, but kind is an instance variable, not static, so the following doesn't work

switch (myEnumValue.kind) {
  case MyEnum.Swap.kind:
    ...
  case MyEnum.LP.kind:
    ...
}

Proposal

export class Swap {
  static readonly discriminator = 0        // <--- make these 2 fields static 
  static readonly kind = "Swap"
  readonly value: SwapValue

  constructor(value: SwapFields) {
    this.value = [new types.SwapInfo({ ...value[0] })]
  }

  toJSON(): SwapJSON {
    return {
      kind: "Swap",
      value: [this.value[0].toJSON()],
    }
  }

  toEncodable() {
    return {
      Swap: {
        _0: types.SwapInfo.toEncodable(this.value[0]),
      },
    }
  }
}

If there's another more idiomatic way of doing this please let me know instead

kklas commented 2 years ago

Oh yea this should definitely be static. Must have slipped my mind when I was implementing. Good suggestion!

I was probably thinking something along the lines of:

if (myEnumValue instanceOf MyEnum.Swap) {
  ...
} else if (myEnumValue instanceOf MyEnum.LP) {
  ...
}

but switch is way more elegant.

JoeHowarth commented 2 years ago

Nice, thanks! Left a little comment on #38