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

TypeScript联合类型Props传参双场景报错,求解决方案

解决FormError组件联合类型的TypeScript报错问题

问题1:传入form.errors.name时的类型不匹配错误

错误原因

form.errors的类型是Partial<Record<keyof TForm, string>>,因此form.errors.name的类型为string | undefined。而你的MessageOnly接口要求message是必填的string,当传入undefined时,TypeScript无法判定当前props属于MessageOnly还是ErrorAndInput(MessageOnly不允许message为undefined,ErrorAndInput又缺少必填的error和input),从而抛出类型不兼容错误。

解决方法

方案1:条件渲染,确保message存在时再渲染

{form.errors.name && <FormError className="mt-2" message={form.errors.name} />}

方案2:调整MessageOnly类型,兼容message为undefined的场景

修改Props定义,让MessageOnly的message可选,同时保持与ErrorAndInput的互斥性:

interface BaseProps {
  className?: string;
}

interface MessageOnly extends BaseProps {
  message?: string;
  error?: never;
  input?: never;
}

interface ErrorAndInput extends BaseProps {
  message?: never;
  error: ErrorResponse;
  input: string;
}

type Props = MessageOnly | ErrorAndInput;

这样TypeScript会通过error和input的存在与否自动区分两种类型分支,避免类型混淆。


问题2:传入error状态时的null类型不兼容错误

错误原因

你的error状态类型是ErrorResponse | null,但ErrorAndInput接口要求error必须是ErrorResponse类型,null不符合该类型约束,因此报错。

解决方法

方案1:条件渲染,确保error不为null时再渲染

{error && <FormError error={error} input="email" className="mt-2" />}

方案2:调整ErrorAndInput类型,允许error为null

如果组件需要处理error为null的场景,可以修改类型定义:

interface ErrorAndInput extends BaseProps {
  message?: never;
  error: ErrorResponse | null;
  input: string;
}

注意:此方案需要确保组件内部逻辑能正确处理error为null的情况。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:15:54