没有重载匹配此调用。 React中的Typescript和StyledComponents

时间:2020-10-28 02:41:02

标签: reactjs typescript gatsby styled-components

好吧,我一直遇到此错误消息,但我不太理解。

Info:React:16.12,Styled-components:5.2.0,Gatsby with typescript:4.0.2。我也有用于反应和样式化组件的@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,共2个,'(props:Pick ,“广告位” | ... 262更多... |“ referrerPolicy”>&{...;}& WorkDisplayProps,“插槽” | ... 270个以上... |“ gridArea”>&Partial <...>,“插槽” | ... 270个以上... |“ gridArea”>&{...; }&{...;}):ReactElement <...>',出现以下错误。 类型'{children:Element; href:字符串;目标:字符串; }”缺少类型'Pick ,“ slot”中的以下属性| ... 262更多... | “ referrerPolicy”>&{...; }和WorkDisplayProps,“广告位” | ... 270更多... | “ gridArea”>&Partial <...>,“插槽” | ... 270更多... | “ gridArea”>':imageSource,imageAlt,linkToProject,projectName和另外2个。 重载2,共2个,'(属性:StyledComponentPropsWithAs <“ a”,任何,WorkDisplayProps,从不>):ReactElement ,字符串| ... 1更多... | (new(props:any)=> Component <...>)>',出现以下错误。 类型'{children:Element; href:字符串;目标:字符串; }”缺少类型'Pick ,“ slot”中的以下属性| ... 262更多... | “ referrerPolicy”>&{...; }和WorkDisplayProps,“广告位” | ... 270更多... | “ gridArea”>&Partial <...>,“插槽” | ... 270更多... | “ gridArea”>':imageSource,imageAlt,linkToProject,projectName和另外2个。

所以,打字稿是否在抱怨,因为我没有在StyledWorkDisplay组件上使用所有道具,还是其他东西?

1 个答案:

答案 0 :(得分: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">
...