reactjs TypeScript:接口不能同时扩展两个类型

5q4ezhmt  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(199)

我正在使用TypeScript编写一个React应用,我的组件使用material-ui,我正在为material-ui的Button组件编写一个自定义 Package 器,如下所示:

import MUIButton, { ButtonProps } from "@material-ui/core/Button";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import classNames from "classnames";
import React, { PureComponent } from "react";
import styles from "./styles";

export interface OwnProps {
  color: "primary" | "danger" | "warning" | "transparent";
  size: "sm" | "lg";
}

export interface Props
  extends WithStyles<typeof styles>,
    OwnProps,
    ButtonProps {}

export class Button extends PureComponent<Props> {
  render() {
    const { color, size, classes, children, ...rest } = this.props;
    const btnClasses = classNames({
      [classes.button]: true,
      [classes[size]]: size,
      [classes[color]]: color
    });
    return (
      <MUIButton {...rest} className={btnClasses}>
        {children}
      </MUIButton>
    );
  }
}

export default withStyles(styles)(Button);

问题是,在这里, prop 的定义抛出错误消息:

Named property 'color' of types 'OwnProps' and 'ButtonProps' are not identical.
[ts]
Interface 'Props' cannot simultaneously extend types 'OwnProps' and 'ButtonProps'.
  Named property 'size' of types 'OwnProps' and 'ButtonProps' are not identical.
Named property 'color' of types 'OwnProps' and 'ButtonProps' are not identical.
[ts]
Interface 'Props' cannot simultaneously extend types 'OwnProps' and 'ButtonProps'.
  Named property 'size' of types 'OwnProps' and 'ButtonProps' are not identical.

如果我改为这样写,这个错误就会消失:

export class Button extends PureComponent<Props & ButtonProps> {

但是,当使用按钮的 prop 颜色和大小抛出错误:

The expected type comes from property 'color' which is declared here on type 'IntrinsicAttributes & Pick<Props & ButtonProps, ...

我怎样才能正确地告诉组件,它有我定义的 prop (OwnProps)以及来自按钮的 prop ?

flseospp

flseospp1#

使用TypeScript的Omit类型从其他类型中排除特定属性:
通过从Type中选取所有属性,然后移除Keys(字符串文本或字符串文本的联合)来构造类型。

import { ButtonProps } from "@material-ui/core/Button";

export type OwnProps = Omit<ButtonProps, "color" | "size"> & {
  color: "primary" | "danger" | "warning" | "transparent";
  size: "sm" | "lg";
}

class MyButton extends React.Component<OwnProps> {
}

相关问题