样式组件和 AS TS2769 的打字稿错误:没有与此调用匹配的重载

时间:2021-06-14 12:48:07

标签: javascript reactjs typescript styled-components

我想要一个简单的组件,我可以设置样式并使用 as 传递 output 元素类型的 prop。将 5styled-components4 用于 TS

但是我收到以下 TS 错误

TS 错误

No overload matches this call.
  Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>, "key" | keyof HTMLAttributes<...>> & { ...; }, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type 'string' is not assignable to type 'undefined'.
  This JSX tag's 'children' prop expects type 'never' which requires multiple children, but only a single child was provided.  TS2769

    11 |     color: #000;
    12 |   `
  > 13 |   return <Component as={as}>{children}</P>
       |          ^
    14 | }
    15 |

这个错误的关键部分在这里我相信 Type 'string' is not assignable to type 'undefined'. 但是我的理解是对于 {as = 'p'} 这是 as 的默认值?

组件

import React, { ReactChildren } from 'react'
import styled from 'styled-components'

export interface TextProps {
  as?: string
  children?: ReactChildren | React.ReactNode | string
}

export const Text = ({ as = 'p', children }: TextProps) => {
  const Component = styled.p`
    color: #000;
  `
  return <Component as={as}>{children}</Component>
}

1 个答案:

答案 0 :(得分:1)

这个有点棘手。首先,对于 type correctly Component 接受 as 道具,您应该为该 as-component 提供正确的输入。第二个问题是 string 的宽度足以导致 never 的任何其他道具的 <Component as={as as string}> 类型。包括 children 道具。因此,必须为至少已知的 html 标签缩小 as 的类型(只要您只允许在那里传递字符串而不是自定义反应组件)。

所以你的代码可能被重写为:

import React, { ReactChildren } from 'react'
import styled from 'styled-components'

type KnownTags = keyof JSX.IntrinsicElements

export interface TextProps {
    as?: KnownTags
    children?: ReactChildren | React.ReactNode | string
}

export const Text = ({ as = 'p', children }: TextProps) => {
    const Component = styled.p`
        color: #000;
    `

    return <Component<typeof as> as={as}>{children}</Component>
}