确定运行时道具打字稿

时间:2020-01-17 08:23:11

标签: reactjs typescript

我正在使用打字稿在setSubscription(false)中创建一个组件。我花了一段时间才弄清楚如何使一个react.js成为两个必选的一项。我正在创建一个prop组件。它应该收到道具中的Labelicon。我过去传递道具的方式是:

title

现在,我知道我可以分别检查props和render中import React, { forwardRef } from 'react'; import clsx from 'clsx'; export interface LabelProps{ className?: string; onClick?: () => void; icon: string, title: string } export const Label = forwardRef<HTMLDivElement, LabelProps>(function( { className, onClick, icon, title }, ref, ) { return ( <div className={clsx(className, 'label')} onClick={onClick} ref={ref}> // My Way to display thing's </div> ); }); export default Label; icon的值。但我希望打字稿不允许我同时传递它们并显示错误。我想将此组件用作:

title

<Label icon={icon} />

但不是以下情况。打字稿应该对此抱怨:

<Label title={title} />

您能告诉我一种实现此目标的方法吗?

1 个答案:

答案 0 :(得分:5)

您可以尝试执行此操作。 这有助于使道具(标题,图标)相互依赖,或者完全没有道具(标题,图标)。

export interface BaseLabelProps extends HTMLAttributes<HTMLLabelElement> {
  className?: string;
}

interface LabelWithIconProps extends BaseLabelProps {
  icon?: string;
  title?: never;
}

interface LabelWithoutIconProps extends BaseLabelProps {
  icon?: never;
  title?: string;
}

export type LabelProps = LabelWithoutIconProps | LabelWithIconProps;