首页 > 解决方案 > TS2739:无法在 typescript 中使用扩展 TippyProps 的自定义 Tippy 包装器

问题描述

我们维护两个独立的存储库作为库。两者都在使用 reactjs。一个是纯组件库,而另一个包含可共享的模块。

我开始在这两个库中集成打字稿。

这是在组件库中命名Tippy.tsx的Tippy 包装器。

import Tooltip, {TippyProps} from '@tippyjs/react'
interface TippyType extends TippyProps {
  hook: string;
  style: Object;
}

const Tippy:React.FC<TippyType> = (props) => {
  const {dataHook = '', style = {}} = props
  function onCreate (instance: any) {
    props?.onCreate?.(instance)
    if (dataHook) {
      instance.props.content.setAttribute('data-hook', dataHook)
    }
    Object.entries(style).forEach(([property, value]) => {
      content.style[property] = value
    })
  }
  return (
    <Tooltip
      { ...props}
      onCreate={onCreate}
    >
      {props.children}
    </Tooltip>
  )
}
export default Tippy

此代码构建成功。但是当我尝试在模块库中使用这个组件时,打字稿只承认钩子样式道具。来自tippy PropTypes 的所有其他道具都会抛出错误。

例如以下代码

<Tippy
  content={value}
  theme='material'
>
  <span className='inline-block m-r-5 to-ellipsis overflow-hidden ws-nowrap'>{value}</span>
</Tippy>

投掷

TS2739:类型'{孩子:元素;内容:字符串;主题:字符串;}' 缺少类型 'TippyType' 的以下属性:hook、'style'

这里是自动生成的声明文件tippy.d.ts

import { TippyProps } from '@tippyjs/react';
import React from 'react';
import './styles.scss';
import 'tippy.js/dist/tippy.css';
interface TippyType extends TippyProps {
    hook: string;
    'style': Object;
}
declare const Tippy: React.FC<TippyType>;
export default Tippy;

这里是TippyProps

标签: reactjstypescripttippyjs

解决方案


TS2739:类型'{孩子:元素;内容:字符串;主题:字符串;}' 缺少类型 'TippyType' 的以下属性:hook、'style'

该错误是在警告您hook,并且style在 Tippy 组件中是强制性的。

interface TippyType extends TippyProps {
    hook: string;   // <--- compulsory 
    style: Object;  // <--- compulsory
}

hook因此,style使用时需要通过Tippy.

<Tippy
    hook=""
    style={{}}
    content={value}
    theme='material'
>
   <span className='inline-block m-r-5 to-ellipsis overflow-hidden ws-nowrap'>{value}</span>
</Tippy>

如果要将 和 标记hookstyle可选,请使用?

interface TippyType extends TippyProps {
  hook?: string;
  style?: Object;
}

推荐阅读