【问题标题】:TypeScript and styled-components: No overload matches this callTypeScript 和 styled-components:没有重载匹配此调用
【发布时间】:2021-11-15 11:39:28
【问题描述】:

我无法理解 TypeScript 抛出的错误消息,也不知道如何修复它。

组件:

import styled, { css } from 'styled-components'

interface IHeader {
  selected: boolean
  children: string
}

const Header = styled.h6<IHeader>`
  color: #fff;
  padding: 5px 0;

  ${(props) =>
    props.selected &&
    css`
      color: #fff;
    `};
`

Header.defaultProps = {
  selected: false,
}

const Component = () => (
  <>
    <Header>children text</Header>
  </>
)

export { Component }

错误信息:

TypeScript error in [...]/Bids.tsx(25,6):
No overload matches this call.
  Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & IHeader, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Property 'selected' is missing in type '{ children: string; }' but required in type 'Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & IHeader, never> & Partial<...>, "theme">'.
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<"h6", DefaultTheme, IHeader, never, "h6", "h6">): ReactElement<StyledComponentPropsWithAs<"h6", DefaultTheme, IHeader, never, "h6", "h6">, string | JSXElementConstructor<...>>', gave the following error.
    Property 'selected' is missing in type '{ children: string; }' but required in type 'Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & IHeader, never> & Partial<...>, "theme">'.  TS2769

    23 | const Bids = () => (
    24 |   <>
  > 25 |     <Header>children text</Header>
       |      ^
    26 |   </>
    27 | )
    28 |

【问题讨论】:

  • AFAICT 编译器正在从这一行 props.selected &amp;&amp; 推断您的 selected 道具,您没有提供,因此它抱怨缺少。将选定的属性添加到标题或在 FC 中键入道具。
  • 有趣,这应该可以运行。你能在bids.tsx中分享Header的导入声明吗

标签: reactjs typescript styled-components


【解决方案1】:

您需要指定selected 是可选的。

interface IHeader {
  selected?: boolean
  children: string
}
import styled, { css } from 'styled-components'

interface IHeader {
  selected?: boolean
  children: string
}

const Header = styled.h6<IHeader>`
  color: #fff;
  padding: 5px 0;

  ${(props) =>
    props.selected &&
    css`
      color: #fff;
    `};
`

Header.defaultProps = {
  selected: false,
}

const Component = () => (
  <>
    <Header>children text</Header>
  </>
)

export { Component }

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 2020-03-28
    • 2022-12-07
    • 2021-02-10
    • 2020-06-29
    • 2020-02-15
    • 2021-05-25
    • 2020-11-28
    • 2021-12-26
    相关资源
    最近更新 更多