near / borsh-js

TypeScript/JavaScript implementation of Binary Object Representation Serializer for Hashing
Apache License 2.0
112 stars 38 forks source link

Enum schema failed with typescript check when (de)serialize #79

Open kayac-chang opened 10 months ago

kayac-chang commented 10 months ago

Depending on the documentation, the enum schema should be

{ enum: [ { struct: { className1: structSchema1 } }, { struct: { className2: structSchema2 } }, ... ] }

Suppose we have a schema like

const borsh_schema = {
  enum: [
    { 
      struct: { 
        transfer: { 
          struct: {
            recipient: 'string',
            amount: "u64",
          },
        }
      }
    },
    { 
      struct: { 
        deploy: {
          struct: {
            contract: { array: { type: "u8" } },
            cbi_version: "u32",
          },
        }
      } 
    },
  ],
}

The type of schema will become (this is intended behavior)

const borsh_schema: {
    enum: ({
        struct: {
            transfer: {
                struct: {
                    recipient: string;
                    amount: string;
                };
            };
            deploy?: undefined;
        };
    } | {
        struct: {
            deploy: {
                struct: {
                    contract: {
                        array: {
                            type: string;
                        };
                    };
                    cbi_version: string;
                };
            };
            transfer?: undefined;
        };
    })[];
}

But this will fail the type check when we want to pass schema to (de)serialize

deserialize(borsh_schema, bytes)
// this will failed the type check

Typescript Playground: https://tsplay.dev/WPM05w

hanakannzashi commented 8 months ago

Enum works for me. You may be interested in borsher

gagdiez commented 8 months ago

@kayac-chang I did not understand the issue, could you please share a repo with the error so I can reproduce it and check on it?