【问题标题】:No overload matches this call. Typescript and StyledComponents in React没有重载匹配此调用。 React 中的 Typescript 和 StyledComponents
【发布时间】:2021-02-10 09:36:24
【问题描述】:

好的,我一直遇到这个错误消息,我不太明白。

信息:React:16.12,样式化组件:5.2.0,带有打字稿的 Gatsby:4.0.2。我也有用于 react 和 styled-components 的 @types。

这是组件。

import React from "react";
import styled from "styled-components";
import WorkDisplayImage from "./WorkDisplayImage";

type WorkDisplayProps = {
  imageSource: string;
  imageAlt: string;
  linkToProject: string;
  linkToCode?: string;
  projectName: string;
  projectType: string;
  gridArea: string;
};

const StyledWorkDisplay = styled.a<WorkDisplayProps>` // <- I defined the type here.
  grid-area: ${(props): string => props.gridArea};
`;

const WorkDisplay = ({
  imageSource,
  imageAlt,
  linkToProject,
  linkToCode,
  projectName,
  projectType,
}: WorkDisplayProps): JSX.Element => (
  <StyledWorkDisplay href={linkToProject} target="noreferrer opener"> // <- But this component is underlined with the error.
    <WorkDisplayImage imageSource={imageSource} imageAlt={imageAlt} />
  </StyledWorkDisplay>
);

export default WorkDisplay;

这是打字稿的错误消息。

没有重载匹配这个调用。

重载 1 of 2, '(props: Pick, "slot" | ... 262 more ... | "referrerPolicy"> & { ...; } & WorkDisplayProps, "slot" | ... 270 更多 ... | "gridArea"> & Partial<...>, "slot" | ... 270 更多 ... | "gridArea"> & { ...; } & { ...; }): ReactElement<...>',给出了以下错误。 类型'{孩子:元素; href:字符串;目标:字符串; }' 缺少以下类型的属性 'Pick, "slot" | ... 262 更多... | "referrerPolicy"> & { ...; } & WorkDisplayProps,“插槽”| ... 270 更多 ... | "gridArea"> & 部分<...>, "slot" | ... 270 更多 ... | "gridArea">':imageSource、imageAlt、linkToProject、projectName 等 2 个。 重载 2 of 2, '(props: StyledComponentPropsWithAs): ReactElement, string | ... 1 更多 ... | (new (props: any) => Component<...>)>',给出了以下错误。 类型'{孩子:元素; href:字符串;目标:字符串; }' 缺少以下类型的属性 'Pick, "slot" | ... 262 更多... | "referrerPolicy"> & { ...; } & WorkDisplayProps,“插槽”| ... 270 更多 ... | "gridArea"> & 部分<...>, "slot" | ... 270 更多 ... | "gridArea">':imageSource、imageAlt、linkToProject、projectName 等 2 个。

那么,打字稿抱怨是因为我没有使用 StyledWorkDisplay 组件上的所有道具,还是其他原因?

【问题讨论】:

    标签: reactjs typescript gatsby styled-components


    【解决方案1】:

    是的,您需要传递您在WorkDisplayProps 中定义的所有非可选道具

    但是,使用父级的所有道具键入链接似乎不正确,您可以使用 Pick 来仅获取您实际使用的链接

    const StyledWorkDisplay = styled.a<Pick<WorkDisplayProps, 'gridArea'>>`
      grid-area: ${(props): string => props.gridArea};
    `;
    
    ...
      projectName,
      projectType,
      gridArea,
    }: WorkDisplayProps): JSX.Element => (
      <StyledWorkDisplay gridArea={gridArea} href={linkToProject} target="noreferrer opener">
    ...
    
    

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 2021-11-15
      • 2020-03-28
      • 1970-01-01
      • 2022-12-07
      • 2020-06-14
      • 2020-06-29
      • 2020-11-28
      • 2020-02-17
      相关资源
      最近更新 更多