typescript 什么是React上下文函数的正确类型声明,以避免linting问题?

nbysray5  于 2023-05-19  发布在  TypeScript
关注(0)|答案(3)|浏览(171)

我正在使用React Context,我有:

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

但我的linter抱怨说:

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

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

nwlls2ji

nwlls2ji1#

如果你只想隐藏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);
7qhs6swi

7qhs6swi2#

您可以使用选项allowArrowFunctions
文档

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

z8dt9xmd3#

如果你使用的是lodash,你可以使用noop函数来绕过linting。

  • 我假设其他库也有类似的功能。*

相关问题