Search code examples
typescripteslinttypescript-eslint

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'. But it's not always works:

This is okay, eslint throws an error:

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

This is NOT okay, eslint see NO problems here:

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?


Solution

  • The rule you are using has an option called allowTypedFunctionExpressions that can be explicitly set to false to get what you want:

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