diff --git a/src/rules/onlyArrowFunctionsRule.ts b/src/rules/onlyArrowFunctionsRule.ts index 5d144558884..ad7734e071b 100644 --- a/src/rules/onlyArrowFunctionsRule.ts +++ b/src/rules/onlyArrowFunctionsRule.ts @@ -56,16 +56,31 @@ export class Rule extends Lint.Rules.AbstractRule { class OnlyArrowFunctionsWalker extends Lint.RuleWalker { public visitFunctionDeclaration(node: ts.FunctionDeclaration) { - if (!node.asteriskToken && !this.hasOption(OPTION_ALLOW_DECLARATIONS)) { - this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING)); + if (!this.hasOption(OPTION_ALLOW_DECLARATIONS)) { + this.failUnlessExempt(node); } super.visitFunctionDeclaration(node); } public visitFunctionExpression(node: ts.FunctionExpression) { - if (!node.asteriskToken) { + this.failUnlessExempt(node); + super.visitFunctionExpression(node); + } + + private failUnlessExempt(node: ts.FunctionLikeDeclaration) { + if (!functionIsExempt(node)) { this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING)); } - super.visitFunctionExpression(node); } } + +/** Generator functions and functions explicitly declaring `this` are allowed. */ +function functionIsExempt(node: ts.FunctionLikeDeclaration) { + return node.asteriskToken || hasThisParameter(node); +} + +function hasThisParameter(node: ts.FunctionLikeDeclaration) { + const first = node.parameters[0]; + return first && first.name.kind === ts.SyntaxKind.Identifier && + (first.name as ts.Identifier).originalKeywordKind === ts.SyntaxKind.ThisKeyword; +} diff --git a/test/rules/only-arrow-functions/allow-declarations/test.ts.lint b/test/rules/only-arrow-functions/allow-declarations/test.ts.lint index 22dbf05bec4..6b0ce7a08a8 100644 --- a/test/rules/only-arrow-functions/allow-declarations/test.ts.lint +++ b/test/rules/only-arrow-functions/allow-declarations/test.ts.lint @@ -20,4 +20,7 @@ function () { function* generator() {} let generator = function*() {} +function hasThisParameter(this) {} +let hasThisParameter = function(this) {} + [0]: non-arrow functions are forbidden diff --git a/test/rules/only-arrow-functions/default/test.ts.lint b/test/rules/only-arrow-functions/default/test.ts.lint index ddacd8e2fc5..bad11677983 100644 --- a/test/rules/only-arrow-functions/default/test.ts.lint +++ b/test/rules/only-arrow-functions/default/test.ts.lint @@ -23,4 +23,7 @@ function () { function* generator() {} let generator = function*() {} +function hasThisParameter(this) {} +let hasThisParameter = function(this) {} + [0]: non-arrow functions are forbidden