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

J. *_*ers 4 typescript reactjs typescript-typings typescript-types react-props

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

问题在于,此处的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.
Run Code Online (Sandbox Code Playgroud)

如果我改为写此错误消失:

export class Button extends PureComponent<Props & ButtonProps> {
Run Code Online (Sandbox Code Playgroud)

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

The expected type comes from property 'color' which is declared here on type 'IntrinsicAttributes & Pick<Props & ButtonProps, ...
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*hko 6

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


}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案实际上并没有解释如何解决问题。该解决方案针对这个问题非常具体,这是可以的,但是添加解释将使其能够为围绕其问题具有类似但独特情况的其他人提供价值。 (2认同)