【问题标题】:What's the proper type declaration of React context functions to avoid linting issues?什么是 React 上下文函数的正确类型声明以避免 linting 问题?
【发布时间】:2021-06-28 13:01:16
【问题描述】:

我正在使用 React Context 并且我有:

const DocumentContext = createContext<
    [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => { }, () => { }]);

但我的 linter 抱怨:

Unexpected empty arrow function @typescript-eslint/no-empty-function

我知道我可以在我的 linting 设置中关闭它,但有正确的方法吗?

【问题讨论】:

  • () =&gt; undefined?和() =&gt; {}一样,但是body不是空的

标签: javascript reactjs typescript eslint use-context


【解决方案1】:

如果您只想抑制 linter 消息,您可以将其声明为:

const DocumentContext = createContext<
    [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => { /* do nothing */ }, () => { /* do nothing */ }]);

或作为:

const DocumentContext = createContext<
    [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>([initVal, () => undefined, () => undefined]);

如果您绝对确定不会在任何地方使用此默认值。即您没有使用此上下文提供者之外的组件,您可以简单地将其定义为:

const DocumentContext = createContext<
    [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>]
>(null as any);

【讨论】:

  • 第三个选项抱怨any
  • 您可以将其替换为“未知”。
【解决方案2】:

您可以使用选项allowArrowFunctions

Documentation

"@typescript-eslint/no-empty-function": ["error", {"allow": ["arrowFunctions"]}],

【讨论】:

  • 这不正是 OP 所说的他们已经知道他们可以做什么吗?
  • 我以为他在 "@typescript-eslint/no-empty-function": "off" 上说的更多
  • 直接的问题是“什么是正确的类型声明......”。所以我怀疑他们是否在寻找 eslint 解决方法,但我想这取决于 OP 来决定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
相关资源
最近更新 更多