描述为打字稿反应组件包装器

Describe to typescript react component wrapper

如何描述 tippy 接受 typescript 将正确使用的任何子项的包装器?

import Tippy, { TippyProps } from '@tippy.js/react'
import React from 'react'
import 'tippy.js/dist/tippy.css'

Tippy.defaultProps = {
  maxWidth: '500px',
}

export const Tooltip: Tooltip = ({ children, content, ...rest }) => {
  if (!children) return null
  if (!content) return children

  return (
    <Tippy content={content} {...rest}>
      {children}
    </Tippy>
  )
}

interface Tooltip {
  (props: MyProps): React.ForwardRefExoticComponent<TippyProps> | null | React.ReactNode
}

interface MyProps {
  content?: string | React.ReactNode
  children?: React.ReactNode
}

这样使用:

   <Tooltip content='Text'>
        <div>123</div>
   </Tooltip>

Typescript 在 return 语句中给出了儿童错误:

Type 'string | number | true | {} | ReactElement ReactElement Component)> | null) | (new (props: any) => Component)> | ReactNodeArray | ReactPortal' is not assignable to type 'ReactElement ReactElement Component)> | null) | (new (props: any) => Component)>'. Type 'string' is not assignable to type 'ReactElement ReactElement Component)> | null) | (new (props: any) => Component)>'.ts(2322) index.d.ts(6, 3): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & TippyProps'

错误指向您的问题:您已将子项声明为 ReactNode,但 ReactNode 可以是字符串,而 Tippy(显然)不会接受字符串子项。请改用 ReactElement。在调试这样的打字稿错误时,添加空格格式通常很有帮助(至少在您习惯阅读它们之前):

Type 
'string | number | true | {} | ReactElement ReactElement Component)> | null) 
| (new (props: any) => Component)> 
| ReactNodeArray 
| ReactPortal' 
is not assignable to type 
'ReactElement ReactElement Component)> | null) 
| (new (props: any) => Component)>'

Type 'string' is not assignable to type 
'ReactElement ReactElement Component)> | null) 
| (new (props: any) => Component)>'

ts(2322) index.d.ts(6, 3): The expected type comes from property 'children' 
which is declared here on type 'IntrinsicAttributes & TippyProps'