英文:
@typescript-eslint/explicit-function-return-type allowHigherOrderFunctions exception returns error with the same args
问题
以下是您的代码的中文翻译部分:
这是我的.eslintrc.json
文件中相关的片段:
"rules": {
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowHigherOrderFunctions": true
}
],
}
使用此配置,我遇到了以下问题:
// ❌ 失败
const arrowFn1 = (): void => {
return;
};
export const arrowHoc = () => arrowFn1;
// ✅ 通过
export const arrowFn2 = () => (): void => {
return;
};
我以为顶部的示例会起作用。这是否符合预期?感谢任何意见!
英文:
Here's the relevant snippet of my .eslintrc.json
:
"rules": {
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowHigherOrderFunctions": true
}
],
}
With this config I am encountering the following:
// ❌ fails
const arrowFn1 = (): void => {
return;
};
export const arrowHoc = () => arrowFn1;
// ✅ passes
export const arrowFn2 = () => (): void => {
return;
};
I thought the top example would work. Is this expected? Thanks for any input!
答案1
得分: 1
这是预期的 - lint 规则故意不跟踪引用以了解可能的变量。该规则的目的是强制您在代码中定义严格的合同 - 这意味着在声明中声明返回类型。
() => (): void => { ... }
在选项下被忽略,因为返回类型可以从代码中的声明中轻松推断出来,而无需任何 IDE 功能 - 它被轻松解读为“返回函数的函数返回 void”。
然而,对于 () => variable
,情况并不相同 - 从代码中读取时,您会读到“返回变量的函数” - 这根本不是严格的合同!
可以争论该规则是否应该忽略它,因为变量是在前一行定义的,但是该规则采用了一种干净、一致的方法,而不是基于大量异常的混乱、令人困惑的方法。例如,想象一下,如果您的代码是这样的
import { arrowFn1 } from 'module';
export const arrowHoc = () => arrowFn1;
arrowHoc
的返回类型是什么?嗯,要弄清楚这一点,首先您需要检查 module
的导出以确定 arrowFn1
的类型,然后您可以知道 arrowHoc
的类型。
如果您使用变量进行间接引用,您需要维护一个单独的、严格的合同来管理您的 HOC。
英文:
This is expected - the lint rule purposely does not track references to understand what variables might be. The point of the rule is to enforce that you're defining strict contracts in your code - which means declaring return types with the declaration.
() => (): void => { ... }
is ignored with the option because the return type is trivially inferred from the declaration in code, without any IDE features - it's trivially read as "a function that returns a function that returns void"
However with () => variable
there isn't the same assurance - instead reading the code you read "a function that returns a variable" - which isn't a strict contract at all!
One could argue that the rule should ignore it because the variable is defined on the preceding line, however the rule takes a clean, consistent approach as opposed to a messy, confusing one based on lots of exceptions. For example imagine instead if your code was
import { arrowFn1 } from 'module';
export const arrowHoc = () => arrowFn1;
What's the return type of arrowHoc
? Well to figure that out first you'll need to inspect the exports of module
to determine the type of arrowFn1
, then you can know the type of arrowHoc
.
If you use variables for indirection, you need to maintain a separate, strict contract for your HOC.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论