我有以下内容:
import React, { Component } from 'react';
import throttle from 'lodash.throttle';
interface Props {
withScroll: boolean;
}
class Image extends Component<Props, {}> {
throttledWindowScroll?: typeof throttle;
componentDidMount() {
const { withScroll } = this.props;
if (withScroll) {
this.throttledWindowScroll = throttle(this.handleWindowScroll, 100);
window.addEventListener('scroll', this.throttledWindowScroll);
}
}
componentWillUnmount() {
if (this.throttledWindowScroll) {
this.throttledWindowScroll.cancel();
}
}
handleWindowScroll = () => {
// Do something
}
render() {
return (
<div />
);
}
}
export default Image;
我还安装了@types/lodash.throttle
,看来一切正常。
我与此组件有关的问题是this.throttledWindowScroll
上的Typescript错误。
Type '(() => void) & Cancelable' is not assignable to type '(<T extends (...args: any) => any>(func: T, wait?: number | undefined, options?: ThrottleSettings | undefined) => T & Cancelable) | undefined'.
Type '(() => void) & Cancelable' is not assignable to type '<T extends (...args: any) => any>(func: T, wait?: number | undefined, options?: ThrottleSettings | undefined) => T & Cancelable'.
Type 'void' is not assignable to type 'T & Cancelable'.
Type 'void' is not assignable to type 'T'.
第二个:
Argument of type '(<T extends (...args: any) => any>(func: T, wait?: number | undefined, options?: ThrottleSettings | undefined) => T & Cancelable) | undefined' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type 'undefined' is not assignable to type 'EventListenerOrEventListenerObject'.
加上.cancel()
方法的使用错误:
Property 'cancel' does not exist on type '<T extends (...args: any) => any>(func: T, wait?: number, options?: ThrottleSettings) => T & Cancelable'.
所以问题出在我的1行代码:throttledWindowScroll?: typeof throttle;
如果我将该定义更改为() => void
,则会收到有关不存在取消方法的错误。
处理这样的导入库的正确方法是什么(注意它确实具有类型定义文件)。
答案 0 :(得分:1)
此定义不正确
throttledWindowScroll?: typeof throttle
使用油门返回T & Cancelable
。另一方面,typeof throttle
是一个函数。更改为
throttledWindowScroll: ReturnType<typeof throttle>