colinhacks/zod

Hard to convert Complex TypeScript Interfaces to Zod Schema with full typing

alan890104 opened this issue · 0 comments

Hi everyone,

I'm working on a TypeScript project and need to convert a set of complex interfaces into a Zod schema for runtime validation. Here's a simplified example of the interfaces I'm working with:

export type WithdrawMode = 'Single' | 'Balanced';

interface BaseWithdraw {
  pool: Address;
  removeLpAmount: bigint;
  queryId?: bigint;
  slippageTolerance?: Slippage;
  minAmountOuts?: IAllocation[] | IAllocation;
  extraPayload?: ExtraPayload;
}

interface NextWithdraw {
  pool: Address;
  mode: WithdrawMode;
  withdrawAsset?: Asset;
  removeLpAmount?: bigint;
}

interface SingleWithdrawBase extends BaseWithdraw {
  mode: 'Single';
}

export interface SingleWithdrawWithNext extends SingleWithdrawBase {
  nextWithdraw: NextWithdraw;
  withdrawAsset?: never;
}

interface SingleWithdrawNoNext extends SingleWithdrawBase {
  nextWithdraw?: NextWithdraw;
  withdrawAsset: Asset;
}

type SingleWithdrawParams = SingleWithdrawWithNext | SingleWithdrawNoNext;

interface BalancedWithdrawParams extends BaseWithdraw {
  mode: 'Balanced';
  nextWithdraw?: NextWithdraw;
}

export type WithdrawParams = SingleWithdrawParams | BalancedWithdrawParams;

My goal is to create Zod schemas for these types, especially for WithdrawParams, which involves unions and nested objects. I'm unsure how to handle the more complex parts, like:

  • Union types (SingleWithdrawParams and BalancedWithdrawParams)
  • Conditional fields (withdrawAsset and nextWithdraw)
  • Optional fields and nested objects (NextWithdraw)

Additionally, I have a specific requirement for the SingleWithdrawParams union:

For SingleWithdrawWithNext, I want the user to fill in only the nextWithdraw field, and not the withdrawAsset field.
For SingleWithdrawNoNext, I want the user to fill in only the withdrawAsset field, and not the nextWithdraw field.
These fields are mutually exclusive.

Could anyone provide guidance or examples of how to translate these interfaces into Zod schemas? Any advice or resources would be greatly appreciated!

Thank you!

Originally posted by @alan890104 in #3885