typescripttypeszodbignumber.js

How to declare an item as a BigNumber with TypeScript & zod


I'm parsing input in TypeScript using zod, and attempting to replace the following interface with a zod type:

interface args {
    quantity: number;
    hugeNum: BigNumber;
} 

Declaring this with zod, I get:

const numConstraints = z.number().min(1);
const parsedPriceType = z.bigint().optional();

const zArgs = z.object({
    quantity: numConstraints,
    parsedPrice?: parsedPriceType,
});

export type myArgs = z.infer<typeof zArgs>;

However, compiling this I get the following error:

        Types of property 'parsedPrice' are incompatible.
          Type 'BigNumber' is not assignable to type 'bigint'.

Is there a BigNumber equivalent in zod that I can use? Or is this a lost cause?


Solution

  • const parsedPriceType = z.bigint().optional();
    

    means an optional bigint, the primitive of the builtin BigInt (zod might allow the wrapped version, might not, I don't know).

    BigNumber comes from the bignumber.js library, which isn't an ECMAScript standard or web standard, so zod doesn't come with a builtin checker for it (especially since that would add dependencies and/or peer dependencies).

    If you want to have a BigNumber in your schema, use z.instanceOf. That would look like

    const parsedPriceType = z.instanceOf(BigNumber).optional();