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)functiontest() {return;}// Should indicate that a number is returnedvarfn=function () {return1;};// Should indicate that a string is returnedvararrowFn= () =>'test';classTest {// Should indicate that no value is returned (void)method() {return; }}
The following patterns are not warnings:
// No return value should be expected (void)functiontest():void {return;}// A return value of type numbervarfn=function ():number {return1;};// A return value of type stringvararrowFn= ():string=>'test';classTest {// No return value should be expected (void)method():void {return; }}
Options
The rule accepts an options object with the following properties:
typeOptions= {// if true, only functions which are part of a declaration will be checked allowExpressions?:boolean; // if true, type annotations are also allowed on the variable of a function expression rather than on the function directly
allowTypedFunctionExpressions?:boolean;// if true, functions immediately returning another function expression will not be checked allowHigherOrderFunctions?:boolean;// if true, concise arrow functions that start with the void keyword will not be checked allowConciseArrowFunctionExpressionsStartingWithVoid?:boolean;};constdefaults= { allowExpressions:false, allowTypedFunctionExpressions:true, allowHigherOrderFunctions:true, allowConciseArrowFunctionExpressionsStartingWithVoid:true,};
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 overrides 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.
{
"rules": {
// disable the rule for all files
"@typescript-eslint/explicit-function-return-type": "off"
},
"overrides": [
{
// enable the rule specifically for TypeScript files
"files": ["*.ts", "*.tsx"],
"rules": {
"@typescript-eslint/explicit-function-return-type": ["error"]
}
}
]
}
allowExpressions
Examples of incorrect code for this rule with { allowExpressions: true }: