如何让条件类型显示所需道具的正确错误

问题描述 投票:0回答:0

我有一个简单的组件,其中两个道具是基于另一个的存在而有条件的。让它工作很简单,但是其他必需道具的错误消息似乎很弱。

组件

type CommonProps = {
  classes?: string | string[];
  htmlFor?: string;

  label: string;
};

type ConditionalProps =
  | {
      optional?: boolean;
      required?: never;
    }
  | {
      optional?: never;
      required?: boolean;
    };

export type LabelProps = CommonProps & ConditionalProps;

export const Label: React.FC<LabelProps> = ({ classes, htmlFor, label, optional, required }) => {
  const _classes = classNames(classes && classes);

  return (
    <Element as={ELEMENT_OPTION_TYPE.LABEL} className={_classes || undefined} htmlFor={htmlFor}>
      {label}
      {required && (
        <Element as={ELEMENT_OPTION_TYPE.SPAN}>
          {"*"}
        </Element>
      )}
      {optional && (
        <Element as={ELEMENT_OPTION_TYPE.SPAN}>
          {"Optional"}
        </Element>
      )}
    </Element>
  );
};

问题

如下面的屏幕截图所示,初始错误消息并未表明需要 label prop。通常,关于所需道具的错误消息会很清楚,但无论出于何种原因,这种模式都不清楚。

我试过的。 我已经尝试了很多排列组合,包括尝试使用接口,但未能找到有效的方法。我也用谷歌搜索并没有找到解决方案。我认为将 CommonProps 更新为如下所示的界面可能会有所帮助,并且结果相同

interface CommonProps {
  classes?: string | string[];
  htmlFor?: string;

  label: string;
};

type ConditionalProps =
  | {
      optional?: boolean;
      required?: never;
    }
  | {
      optional?: never;
      required?: boolean;
    };

export type LabelProps = CommonProps & ConditionalProps;

提前致谢。

javascript reactjs typescript typescript2.0
© www.soinside.com 2019 - 2024. All rights reserved.