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

如何基于同对象属性推导TypeScript函数参数类型?

问题解决:让Zod Schema类型自动推导为回调函数参数

当前代码中getNextStep的参数d被推导为any,无法自动关联到同一对象中schema的结构类型。要实现类型自动推导,需要调整类型定义,确保每个步骤的getNextStep参数类型与自身的schema强绑定。

核心问题分析

原代码的Step泛型类型虽然定义了TSchema与getNextStep的关联,但在Config映射类型中,TypeScript无法为每个独立步骤条目正确推导TSchema,导致getNextStep的参数类型丢失。

修正方案

通过重构类型定义,使用映射类型为每个步骤条目单独关联schema和getNextStep的类型关系:

import { ComponentType } from "react";
import { z } from "zod";

// 定义基础步骤类型,包含组件和schema
type BaseStep<TProps = unknown> = {
  component: ComponentType<TProps>;
  schema: z.ZodType;
};

// 扩展基础步骤类型,将getNextStep的参数与当前步骤的schema绑定
type StepWithNext<T extends BaseStep> = T & {
  getNextStep?: (data: z.infer<T["schema"]>) => string;
};

// 创建配置的函数,使用映射类型确保每个步骤的类型关联
function createConfig<TConfig extends Record<string, BaseStep>>(
  config: { [K in keyof TConfig]: StepWithNext<TConfig[K]> }
) {
  return config;
}

// 使用示例
const config = createConfig({
  Step1: {
    component: ({ orgId }: { orgId: string }) => null,
    schema: z.object({ userId: z.string() }),
    getNextStep: (d) => "Step2", // d现在被正确推导为 { userId: string }
  },
  Step2: {
    component: ({ userId }: { userId: string }) => null,
    schema: z.unknown(),
    getNextStep: () => "Step1", // 如果使用参数,类型会是unknown
  },
});

关键改动说明

  1. 拆分类型:将Step拆分为BaseStep(基础结构)和StepWithNext(关联schema与回调参数),明确类型关联关系。
  2. 映射类型约束:createConfig函数的参数使用映射类型,为每个步骤条目单独推导schema对应的类型,确保getNextStep的参数类型与当前步骤的schema完全匹配。
  3. 自动推导:TypeScript现在可以为每个步骤的getNextStep参数自动推导正确的类型,无需手动指定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:19:57