首页 > 解决方案 > 当尝试使用打字稿定义功能组件以与样式化组件做出反应时,会出现“没有重载匹配此调用”的错误。

问题描述

沙盒 https://codesandbox.io/s/typescript-type-checking-question-0b42t

代码

type BadgeTypes = {
  success: string;
  secondary: string;
  alert: string;
  text: string;
};

type Theme = {
  fonts?: object;
  borderRadius: string;
  primary?: object;
  accent?: object;
  action?: object;
  stories?: object;
  checkbox?: object;
  badge: BadgeTypes;
  button?: object;
  page?: object;
  states?: object;
  modal?: object;
};
interface Props {
  theme: Theme;
  large: boolean;
  type: keyof BadgeTypes;
}
const StyledBadge = styled.span<Props>`
  display: inline-block;
  border-radius: ${(props: Props): string => props.theme.borderRadius};
  text-align: center;
  color: ${(props: Props): string => props.theme.badge.text};
  font-size: ${(props: Props): string => (props.large ? `1.4rem` : `1rem`)};
  padding: ${(props: Props): string =>
    props.large ? `0 .8rem` : `0.2rem 0.6rem 0.3rem 0.6rem`};
  background: ${(props: Props): string => props.theme.badge[props.type]};
`;
interface BadgeProps {
  children: React.ReactChildren;
  // any other props that come into the component
}

const Badge = ({
  children,
  ...props
//problem likely the line below
}: BadgeProps): React.FunctionComponentElement<BadgeProps> => (
  <StyledBadge {...props}>{children}</StyledBadge>
);

错误是

No overload matches this call.
  Overload 1 of 2, '(props: Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "slot" | "style" | ... 253 more ... | "is"> & { ...; } & Props, "slot" | ... 258 more ... | "large"> & Partial<...>, "slot" | ... 257 more ... | "large"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type '{ children: ReactChildren; }' is missing the following properties from type 'Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "slot" | "style" | ... 253 more ... | "is"> & { ...; } & Props, "slot" | ... 258 more ... | "large"> & Partial<...>, "slot" | ... 257 more ... | "large">': type, large
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<"span", any, Props, never>): ReactElement<StyledComponentPropsWithAs<"span", any, Props, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.
    Type '{ children: ReactChildren; }' is missing the following properties from type 'Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "slot" | "style" | ... 253 more ... | "is"> & { ...; } & Props, "slot" | ... 258 more ... | "large"> & Partial<...>, "slot" | ... 257 more ... | "large">': type, largets(2769)

我知道这很可能是我放在那里的错误函数返回类型的结果BadgeProps):但是经过几次谷歌搜索后我找不到合适的类型。

标签: javascriptreactjstypescript

解决方案


更多的是关于你的BadgeProps,它们与 没有任何关系Props。既然StyledBadge有 type 的 props Props,TypeScript 就会大喊大叫!

为了解决这个问题,我制作了一个带有必要修复的小代码沙箱

我还对您声明Badge组件的方式进行了一些小改动 :)


推荐阅读