【发布时间】:2019-04-07 16:18:43
【问题描述】:
我正在使用 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 时,道具颜色和大小会抛出错误:
The expected type comes from property 'color' which is declared here on type 'IntrinsicAttributes & Pick<Props & ButtonProps, ...
我怎样才能正确地告诉组件它具有我定义的道具 (OwnProps) 以及像往常一样来自 Button 的道具?
【问题讨论】:
-
请包括有错误的代码和错误的全文(或至少主要部分,“类型X不可分配给类型Y”)
-
@jcalz 我编辑了这个问题????谢谢你的帮助!
标签: reactjs typescript typescript-typings react-props typescript-types