githubEdit

Require explicit return types on functions and class methods (explicit-function-return-type)

Explicit types for function return values makes it clear to any calling code what type is returned. This ensures that the return value is assigned to a variable of the correct type; or in the case where there is no return value, that the calling code doesn't try to use the undefined value when it shouldn't.

Rule Details

This rule aims to ensure that the values returned from functions are of the expected type.

The following patterns are considered warnings:

// Should indicate that no value is returned (void)
function test() {
  return;
}

// Should indicate that a number is returned
var fn = function () {
  return 1;
};

// Should indicate that a string is returned
var arrowFn = () => 'test';

class Test {
  // Should indicate that no value is returned (void)
  method() {
    return;
  }
}

The following patterns are not warnings:

Options

The rule accepts an options object with the following properties:

Configuring in a mixed JS/TS codebase

If you are working on a codebase within which you lint non-TypeScript code (i.e. .js/.jsx), you should ensure that you should use ESLint overridesarrow-up-right to only enable the rule on .ts/.tsx files. If you don't, then you will get unfixable lint errors reported within .js/.jsx files.

allowExpressions

Examples of incorrect code for this rule with { allowExpressions: true }:

Examples of correct code for this rule with { allowExpressions: true }:

allowTypedFunctionExpressions

Examples of incorrect code for this rule with { allowTypedFunctionExpressions: true }:

Examples of additional correct code for this rule with { allowTypedFunctionExpressions: true }:

allowHigherOrderFunctions

Examples of incorrect code for this rule with { allowHigherOrderFunctions: true }:

Examples of correct code for this rule with { allowHigherOrderFunctions: true }:

allowConciseArrowFunctionExpressionsStartingWithVoid

Examples of incorrect code for this rule with { allowConciseArrowFunctionExpressionsStartingWithVoid: true }:

Examples of correct code for this rule with { allowConciseArrowFunctionExpressionsStartingWithVoid: true }:

When Not To Use It

If you don't wish to prevent calling code from using function return values in unexpected ways, then you will not need this rule.

Further Reading

Last updated