1

如何描述tippy接受打字稿将正确使用的任何孩子的包装器?

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>

打字稿在返回语句中给了我孩子的错误:

键入'字符串 | 号码 | 真实 | {} | ReactElement ReactElement 组件)> | 空) | (新(道具:任何)=> 组件)> | 反应节点数组 | ReactPortal' 不可分配给类型 'ReactElement ReactElement 组件)> | 空) | (新(道具:任何)=> 组件)>'。类型 'string' 不可分配给类型 'ReactElement ReactElement 组件)> | 空) | (new (props: any) => Component)>'.ts(2322) index.d.ts(6, 3): 预期的类型来自属性 'children',它在类型 'IntrinsicAttributes & TippyProps' 上声明

4

1 回答 1

1

错误指出了问题所在:您已将 children 声明为 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'
于 2019-11-26T15:24:24.970 回答