决定运行时道具打字稿

Muh*_*han 2 typescript reactjs

我正在react.js使用打字稿创建一个组件。我被困了一段时间,想弄清楚如何让prop两个中的一个成为强制性的。我正在创建一个Label组件。它应该接收一个icontitle在道具中。我过去传递道具的方式是:

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;
Run Code Online (Sandbox Code Playgroud)

现在,我知道我可以分别检查props 和 render 中的icon和的值title。但我希望打字稿不允许我通过它们并显示错误。我想将此组件用作:

<Label icon={icon} />
Run Code Online (Sandbox Code Playgroud)

或者

<Label title={title} />
Run Code Online (Sandbox Code Playgroud)

但不是如下。打字稿应该抱怨这个:

<Label icon={icon} title={title} />
Run Code Online (Sandbox Code Playgroud)

你能告诉我一种方法来实现这一目标吗?

Zun*_*iaz 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;
Run Code Online (Sandbox Code Playgroud)