【问题标题】:TypeScript: 'handleFirstTab' was used before it was defined @typescript-eslint/no-use-before-defineTypeScript:在定义 @typescript-eslint/no-use-before-define 之前使用了“handleFirstTab”
【发布时间】:2020-08-01 07:29:40
【问题描述】:

我在 React 组件中有以下代码,TypeScript 给出以下错误:

'handleFirstTab' was used before it was defined @typescript-eslint/no-use-before-define

如果我将两个函数拆分为单独的文件并将它们相互导入,那么错误就会消失。有没有一种方法可以让我在同一个文件中同时拥有这两个函数而不禁用@typescript-eslint/no-use-before-define,并且错误会消失。谢谢。

  const handleMouseDownOnce = (): void => {
    document.body.classList.remove('user-is-tabbing')
    window.removeEventListener('mousedown', handleMouseDownOnce)
    window.addEventListener('keydown', handleFirstTab)
  }

  const handleFirstTab = (e: KeyboardEvent): void => {
    if (e.code === 'Tab') {
      document.body.classList.add('user-is-tabbing')
      window.removeEventListener('keydown', handleFirstTab)
      window.addEventListener('mousedown', handleMouseDownOnce)
    }
  }

【问题讨论】:

  • 除非你想为这个特定的实例添加一个 ESLint 禁用注释,否则你在同一个文件中定义这些函数的任何方式都将违反 ESLint 规则,因为无论你先声明哪个,它将始终引用未定义的第二个函数。我不知道你的完整实现,但可能值得考虑一种方法来重构这两种方法,这样它们就不会相互引用。
  • 您是否尝试过使用函数声明 (function handleMouseDownOnce() { ... }) 而不是函数表达式 (const handleMouseDownOnce = () => { ... })?
  • 谢谢,@Shlang 我已经尝试过函数声明,但没有帮助。

标签: typescript types type-conversion


【解决方案1】:

当您使用 constlet 定义变量(或函数)时,它不会是 Hoist 使用 function 关键字或使用 var 的函数声明

如果您想将它们都放在同一个文件中,您需要更改您的代码,如下所示:

  function handleMouseDownOnce(): void {
    document.body.classList.remove('user-is-tabbing')
    window.removeEventListener('mousedown', handleMouseDownOnce)
    window.addEventListener('keydown', handleFirstTab)
  }

  function handleFirstTab(e: KeyboardEvent): void{
    if (e.code === 'Tab') {
      document.body.classList.add('user-is-tabbing')
      window.removeEventListener('keydown', handleFirstTab)
      window.addEventListener('mousedown', handleMouseDownOnce)
    }
  }

【讨论】:

  • 谢谢@taghi-khavari 它不起作用。我仍然有同样的错误。
  • 所以没有办法,您必须禁用 @typescript-eslint/no-use-before-define 或在文件中使用 @ts-ignore 因为您明确表示要出错什么时候发生的
  • @SyedNisarHassan 您可能需要更改此规则的配置以避免在这种特殊情况下出现错误"@typescript-eslint/no-use-before-define": ["error", { "functions": false }]。这是安全的,因为函数声明被提升了。
猜你喜欢
  • 2020-03-23
  • 2021-12-30
  • 2021-06-25
  • 1970-01-01
  • 2017-09-11
  • 2021-05-04
  • 1970-01-01
  • 2020-01-25
  • 2021-02-20
相关资源
最近更新 更多