TypeScript:接口不能同时扩展两种类型 [英] TypeScript: Interface cannot simultaneously extends two types

查看:26
本文介绍了TypeScript:接口不能同时扩展两种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TypeScript 编写 React 应用程序.我为我的组件使用 material-ui.我正在为 material-ui 的 Button 组件编写一个自定义包装器.它看起来像这样:

I'm writing a React app using TypeScript. I use material-ui for my components. I'm writing a custom wrapper for material-ui's Button component. It looks like this:

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的定义抛出了错误信息:

The problem is that here that the definition of Props throw the error message:

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.

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

This error goes away if I instead write:

export class Button extends PureComponent<Props & ButtonProps> {

但是当使用 Button 时,道具颜色和大小会抛出错误:

But then when using the Button the props color and size throw the error:

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

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

How can I correctly tell the component that it has the the Props I defined (OwnProps) as well as the props that come from the Button as usual?

推荐答案

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


}

这篇关于TypeScript:接口不能同时扩展两种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆