如何在 Typescript 中强制执行对象方法的显式返回类型?

Spe*_*ord 2 typescript eslint typescript-eslint

我想强制执行显式声明代码中所有函数和方法的返回类型。

所以我设定了'@typescript-eslint/explicit-function-return-type': 'error'。但它并不总是有效:

这没问题,eslint抛出错误:

const obj = {
  fn() {   // <---- no return type, so "Missing return type on function" error
    return 2;
  }
};
Run Code Online (Sandbox Code Playgroud)

这是不行的,eslint这里没有问题:

const obj: Record<string, any> = { // <---- But if I declare a type of an object...
  fn() {   // <---- ...this is throws no error anymore!
    return 2;
  }
};
Run Code Online (Sandbox Code Playgroud)

如何确保不存在没有显式返回类型定义的方法?

GOT*_*O 0 7

您正在使用的规则有一个名为的选项allowTypedFunctionExpressions,可以显式设置false为获得您想要的内容:

...
"rules": {
    ...
    "@typescript-eslint/explicit-function-return-type": ["error", { "allowTypedFunctionExpressions": false }],
    ...
},
...
Run Code Online (Sandbox Code Playgroud)