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

2023-12-29

我正在使用 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, ...

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


使用 TypeScript 的Omit type https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys从另一种类型中排除特定属性:

通过从 Type 中选取所有属性,然后删除 Key(字符串文字或字符串文字的并集)来构造类型。

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> {
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript:接口不能同时扩展两种类型 的相关文章

随机推荐