【问题标题】:How can I fix this @typescript-eslint warning using an arrow function with "this" inside?如何使用内部带有“this”的箭头函数修复此@typescript-eslint 警告?
【发布时间】:2021-06-15 08:54:29
【问题描述】:

我正在使用这个打字稿代码:

const tryThis = () => {
  const methods = {
    Login() {
      console.log("I'm Login()")
    },

    OnInit() {
      this.Login()
    }
  }

  return methods
}

@typescript-eslint 警告我:

  1. Unsafe member access .Login on an any value. eslint@typescript-eslint/no-unsafe-member-access

  2. Unsafe call of an any typed value. eslint@typescript-eslint/no-unsafe-call

为什么?

我该如何解决这个问题?

【问题讨论】:

  • 您可以在方法定义中明确提供 this 的类型:例如,(this: { Login: () => void, OnInit: () => void })。不过,我不确定您为什么会收到该警告; TS 似乎能够为 this 本身推断出该类型。

标签: typescript eslint typescript-eslint


【解决方案1】:

根据您的 eslint 配置,linter 可能不允许访问具有 any 类型的成员。要解决此问题,您可以在 .eslintrc.js 文件中使用 "no-unsafe-any": false 检查 here 或键入您的函数。

type ThisType = () => {
    Login(): void;
    OnInit(): void;
}

const tryThis:ThisType = () => {
  const methods = {
    Login() {
      console.log("I'm Login()")
    },

    OnInit() {
      this.Login()
    }
  }

  return methods
}

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 2019-12-17
    • 2018-04-20
    • 2017-03-10
    • 2020-05-05
    • 2017-09-13
    • 1970-01-01
    • 2023-02-04
    • 2021-04-22
    相关资源
    最近更新 更多