metaplex-foundation / solita

Genrates an SDK API from solana contract IDL.
Apache License 2.0
140 stars 32 forks source link

Fix dataEnum cast #102

Closed lorisleiva closed 1 year ago

lorisleiva commented 1 year ago

This PR aims to make the type of generated dataEnum slightly stricter by providing the second type parameter of Beet<T, V>.

When type V is missing, it defaults to Partial<T> which makes little sense in the case of a dataEnum since we've got to provide the __kind in order to know how to serialise it.

This causes issues when using dataEnum types in other types such as the map type which expect both its keys and values to be of type Beet<K, K> and Beet<V, V> respectively.

Here's an example.

Before

export const payloadTypeBeet = beet.dataEnum<PayloadTypeRecord>([
  // ...
]) as beet.FixableBeet<PayloadType>;

When used in a map type, it throws a TypeError.

export const payloadBeet = new beet.FixableBeetArgsStruct<Payload>(
  [['map', beet.map(payloadKeyBeet, payloadTypeBeet)]],
                                 // ^-------------- TypeError: '__kind' is optional in type Partial<...>
  'Payload',
);

After

export const payloadTypeBeet = beet.dataEnum<PayloadTypeRecord>([
  // ...
]) as beet.FixableBeet<PayloadType, PayloadType>;

Now the following type works.


export const payloadBeet = new beet.FixableBeetArgsStruct<Payload>(
  [['map', beet.map(payloadKeyBeet, payloadTypeBeet)]],
  'Payload',
);