如何使用打字稿和情感在Box组件上修复``属性'颜色'的类型不兼容''

问题描述

我正在尝试在新项目上使用通用的Box React组件。这将是所有其他组件的基础。我正在使用样式化的系统,情感以及最终的theme-ui来处理我所有组件的主题化和样式化。

我的根Box组件如下所示:

import styled from '@emotion/styled';
import {
  compose,space,layout,flexbox,border,position,color,SpaceProps,ColorProps,LayoutProps,FlexboxProps,BorderProps,PositionProps,} from 'styled-system';

export type BoxProps = SpaceProps &
  ColorProps &
  LayoutProps &
  FlexboxProps &
  BorderProps &
  PositionProps;

export const Box = styled.div<BoxProps>(
  {
    boxSizing: 'border-box',minWidth: 0,},compose(space,position)
);

我正在使用样式函数及其来自样式系统的相关类型,以创建一个Box组件,该组件接受空间,颜色,布局,flexbox,边框和位置道具。

我得到的错误仅在color道具上发生。删除后,我不会收到任何错误。

TS错误为:

Type 'BoxProps' does not satisfy the constraint 'Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>,HTMLDivElement>,"color">,"color">'.
  Types of property 'color' are incompatible.
    Type 'string | number | symbol | (string | number | symbol | null)[] | { [x: string]: string | number | symbol | undefined; [x: number]: string | number | symbol | undefined; } | null | undefined' is not assignable to type 'string | undefined'.
      Type 'null' is not assignable to type 'string | undefined'.ts(2344)

这似乎只是从样式组件转换为情感时的一个问题,因此我不确定是否缺少某些东西来正确利用情感的类型?

解决方法

如果“type”和“as”类型有错误,您应该在将它们插入样式组件之前重新定义这些类型。也许,如果您尝试重写您的道具,它会有所帮助。我的例子:

/* Button component */
const Button: React.FC<ButtonProps> = ({
  isLoading,children,// should redefine this types,because React.HTMLProps<HTMLButtonElement> has incompatible similar types
  type = 'button',as = undefined,...props
}: ButtonProps,...others) => {
  return (
    <StyledButton {...props} {...others}>
      {isLoading ? 'Loading...' : children}
    </StyledButton>
  );
};

export default Button;

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...