【发布时间】:2019-06-10 15:29:41
【问题描述】:
我有以下组件:
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,我会收到有关其上不存在取消方法的错误。
处理这样的导入库的正确方法是什么(注意它确实有一个类型定义文件)。
【问题讨论】:
标签: javascript reactjs typescript lodash