简体   繁体   English

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

[英]How to enforce explicit return type of object's methods in Typescript?

I want to enforce do explicit declare a return type of all functions and methods in the code.我想强制执行显式声明代码中所有函数和方法的返回类型。

So I set '@typescript-eslint/explicit-function-return-type': 'error' .所以我设置'@typescript-eslint/explicit-function-return-type': 'error' But it's not always works:但它并不总是有效:

This is okay, eslint throws an error:没关系, eslint报错:

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

This is NOT okay, eslint see NO problems here:这不行, eslint在这里看到没有问题:

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

How can I make sure that there is no methods without explicit return type definition?如何确保没有没有明确的返回类型定义的方法?

The rule you are using has an option called allowTypedFunctionExpressions that can be explicitly set to false to get what you want:您正在使用的规则有一个名为allowTypedFunctionExpressions的选项,可以将其显式设置为false以获得您想要的:

...
"rules": {
    ...
    "@typescript-eslint/explicit-function-return-type": ["error", { "allowTypedFunctionExpressions": false }],
    ...
},
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM