【问题标题】:React component Typescript for lodash helper用于 lodash 助手的 React 组件 Typescript
【发布时间】: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;

如果我将该定义更改为 () =&gt; void,我会收到有关其上不存在取消方法的错误。

处理这样的导入库的正确方法是什么(注意它确实有一个类型定义文件)。

【问题讨论】:

    标签: javascript reactjs typescript lodash


    【解决方案1】:

    这个定义是错误的

    throttledWindowScroll?: typeof throttle
    

    使用油门返回T &amp; Cancelable。另一方面,typeof throttle 是一个函数。改成

    throttledWindowScroll: ReturnType<typeof throttle>
    

    【讨论】:

    • 尝试在静态属性定义中引用 handleWindowScroll 会引发此错误:Cannot find name 'handleWindowScroll'.
    • 你可以试试this.handleWindowScroll或者直接使用type。
    • 第一个选项抛出这个错误:Cannot find name 'this'. 第二个选项抛出这个错误:Cannot find name 'Cancelable'.
    • 好的,忘记第一个并从类型定义中导入可取消的类型。尝试将其完全限定为 lodash.Cancelable
    • 消除所有错误的优秀工具!感谢您找到此解决方案
    猜你喜欢
    • 2018-05-09
    • 2021-10-02
    • 2023-01-24
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多