You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elysia中定义递归Schema遇初始化错误的解决方案咨询

解决Elysia递归Schema初始化错误问题

错误原因

你遇到的ReferenceError: Cannot access 'variantSchema' before initialization,核心原因是在t.Recursive的回调函数里直接引用了尚未完成初始化的variantSchema变量。

虽然你用了t.Recursive来处理递归结构,但回调执行时,外部的variantSchema还处于赋值过程中,JS引擎会判定你在变量初始化完成前就访问它,因此抛出错误。TypeBox(Elysia的t工具基于TypeBox)的递归机制要求通过回调参数来引用自身,而非直接使用外部变量。

修复方案

将t.Recursive的回调函数改为接收一个self参数,用这个参数代替直接引用variantSchema来定义递归字段。

修正后的代码

import { t } from "elysia";

export const variantSchema = t.Recursive((self) => // 接收self参数
  t.Object({
    _id: t.Optional(t.String()),
    ref: t.String(),
    name: t.String({
      minLength: 1,
      error: "Name must be at least 1 character long",
    }),
    additionalPrice: t.Number({
      minimum: 0,
      error: "Additional price must be at least 0",
    }),
    discountPrice: t.Optional(
      t.Number({
        minimum: 0,
        error: "Discount price must be at least 0",
      }),
    ),
    currentStock: t.Number({
      minimum: 0,
      error: "Current stock must be at least 0",
    }),
    children: t.Optional(t.Array(self)), // 使用self代替variantSchema
  }),
);

export const saveVariants = t.Object({
  productId: t.String(),
  variants: t.Array(variantSchema),
});

修改后,递归引用会通过self参数正确指向Schema自身,彻底避免初始化顺序导致的错误。

内容的提问来源于stack exchange,提问作者Moe24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 15:45:57