如何解决TS2739:无法使用自定义 Tippy 包装器在打字稿中扩展 TippyProps
我们维护两个独立的存储库作为库。两者都在使用 reactjs。一个是纯组件库,另一个包含可共享的模块。
我开始在这两个库中集成打字稿。
这是组件库中的 Tippy 包装器命名 Tippy.tsx。
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
此代码构建成功。但是当我尝试在模块库中使用这个组件时,typescript 只承认 hook 和 style 道具。来自tippy PropTypes 的所有其他道具都会抛出错误。
例如以下代码
<Tippy
content={value}
theme='material'
>
<span className='inline-block m-r-5 to-ellipsis overflow-hidden ws-Nowrap'>{value}</span>
</Tippy>
投掷
TS2739:类型 '{children: Element;内容:字符串;主题:字符串; }' 缺少类型 'TippyType' 中的以下属性:hook,'style'
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
解决方法
TS2739:类型 '{children: Element;内容:字符串;主题:字符串; }' 缺少类型 '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>
如果要将 hook
和 style
标记为可选,请使用 ?
:
interface TippyType extends TippyProps {
hook?: string;
style?: Object;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。