使用TypeScript分解功能参数中的道具

hal*_*nes 1 typescript reactjs

我正在尝试使用TypeScript的组件库,并尝试将React中的无状态功能组件从ES6 / JavaScript转换为TypeScript。我想知道如何在传递函数参数的同时仍然能够在函数外部解构props的同时避免重复自己。

我的组件当前如下所示:

const allowedColors = {
  warning: "fa fa-exclamation",
  info: "fa fa-info",
  success: "fa fa-check",
  danger: "fa fa-minus-circle"
};

const AlertIcon = ({ className, color, ...props }) => (
  <FontAwesomeIcon
    {...props}
    iconClassName={allowedColors[color]}
    className={classNames(`alert-icon-${color}`, className)}
    aria-hidden="true"
    data-ut="alert-icon"
  />
);

AlertIcon.propTypes = {
  className: PropTypes.string,
  color: PropTypes.oneOf(Object.keys(allowedColors)).isRequired
};
Run Code Online (Sandbox Code Playgroud)

我将如何将其重构为TypeScript?

Uzi*_*Uzi 10

type Color = "warning" | 'info'| 'success' | 'danger'

interface IProps {
  color: Color
}

const AlertIcon = ({ className, color, ...props }: IProps) => { ... }
Run Code Online (Sandbox Code Playgroud)

现在,当您使用AlertIconcolor道具的类型必须为Color

来考虑传递HTML属性,就像className您可以这样做:

interface IProps extends HTMLAttributes<HTMLElement> { ... }
Run Code Online (Sandbox Code Playgroud)

HTMLElement您的元素类型在哪里。

  • 需要将 `[x: string]: any` 添加到您的 `IProps` (6认同)
  • 有一个更好的方法来实现这一目标。看到我的编辑。无论如何,您的建议都允许传递不是非常安全的未声明属性。 (2认同)