javascript - 用于 lodash 助手的 React 组件 Typescript

标签 javascript reactjs typescript lodash

我有以下组件:

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 & Cancelabletypeof throttle 另一方面是一个函数。改成

throttledWindowScroll: ReturnType<typeof throttle>

关于javascript - 用于 lodash 助手的 React 组件 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529316/

相关文章:

javascript - 在 NetSuite 中向自定义交易表单添加操作

javascript - 从 HTTP POST 请求中检索 JSON

reactjs - 在 redux-Saga 中重新连接到 webSocket 服务器的标准方法?

reactjs - 我正在尝试使用 React hook 表单上传文件,并且使用了 useController 函数,但出现错误

reactjs - 如何动态定位 IonPopover 以从按钮出现?

javascript - typescript 错误 - 类型上不存在属性 'permission'

Javascript 间歇性失败,但在刷新页面时可以工作

javascript - PrettyPhoto 模式打开时禁用键盘导航 (Wordpress)

html - Deck.gl (Mapbox) StaticMap 不会调整大小 - 覆盖屏幕上的所有内容

tsconfig.json 中的 typescript outDir 设置不起作用