我有以下组件:
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'.
所以问题出在我的第一行代码上:throttledWindowScroll?: typeof throttle;
如果我将该定义更改为 () => void
,我会收到一条关于取消方法不存在的错误。
像这样处理导入库的正确方法是什么(注意它确实有一个类型定义文件)。
最佳答案
这个定义不正确
throttledWindowScroll?: typeof throttle
使用限制返回 T & Cancelable
。 typeof throttle
另一方面是一个函数。改成
throttledWindowScroll: ReturnType<typeof throttle>
关于javascript - 用于 lodash 助手的 React 组件 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529316/