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

时间:2018-11-03 20:26:03

标签: reactjs typescript typescript-typings react-props typescript-types

我正在使用TypeScript编写React应用。我将material-ui用于组件。我正在为material-ui的Button组件编写自定义包装。看起来像这样:

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);

问题在于,此处的Props定义会引发错误消息:

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> {

但是当使用按钮时,道具的颜色和大小会引发错误:

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

如何像往常一样正确地告诉组件它具有我定义的道具(OwnProps)和来自Button的道具?

1 个答案:

答案 0 :(得分:2)

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> {


}