reactjs - TypeScript:接口(interface)不能同时扩展两种类型

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

但是当使用 Button 时, Prop 颜色和尺寸会抛出错误:

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

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

最佳答案

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

关于reactjs - TypeScript:接口(interface)不能同时扩展两种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135199/

相关文章:

typescript - 如何从字符串数组构建 Typescript 类型?

javascript - 是否有必要为 typescript 中使用的每个 JS 库提供类型/定义文件?

javascript - React 动态表单输入 useRef typeError

javascript - ReactJS:Dom 以错误的顺序渲染

javascript - Typescript 中用于对数组进行自定义排序的比较器

typescript - 预期有 3 个类型参数但得到 1 个但它应该推断出 2 种类型

javascript - 类型 'any ' 的参数不可分配

javascript - 将函数的返回值分配给React Native中的对象属性

javascript - React 中的计算器项目在计算表达式后按下数字时发生。附加所需的数字而不是添加

javascript - 通过脚本使用Office365 Excel打开CSV