Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Adding "allow-declarations" to only-arrow-functions #1452

Merged
merged 12 commits into from
Aug 9, 2016
24 changes: 20 additions & 4 deletions src/rules/onlyArrowFunctionsRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,29 @@ import * as ts from "typescript";

import * as Lint from "../lint";

const OPTION_ALLOW_DECLARATIONS = "allow-declarations";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "only-arrow-functions",
description: "Disallows traditional (non-arrow) function expressions.",
rationale: "Traditional functions don't bind lexical scope, which can lead to unexpected behavior when accessing 'this'.",
optionsDescription: "Not configurable.",
options: null,
optionExamples: ["true"],
optionsDescription: Lint.Utils.dedent`
One argument may be optionally provided:

* \`"${OPTION_ALLOW_DECLARATIONS}"\` allows standalone function declarations.
`,
options: {
type: "array",
items: {
type: "string",
enum: [OPTION_ALLOW_DECLARATIONS],
},
minLength: 0,
maxLength: 1,
},
optionExamples: ["true", `[true, "${OPTION_ALLOW_DECLARATIONS}"]`],
type: "typescript",
};
/* tslint:enable:object-literal-sort-keys */
Expand All @@ -41,7 +55,9 @@ export class Rule extends Lint.Rules.AbstractRule {

class OnlyArrowFunctionsWalker extends Lint.RuleWalker {
public visitFunctionDeclaration(node: ts.FunctionDeclaration) {
this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
if (!this.hasOption(OPTION_ALLOW_DECLARATIONS)) {
this.addFailure(this.createFailure(node.getStart(), "function".length, Rule.FAILURE_STRING));
}
super.visitFunctionDeclaration(node);
}

Expand Down
20 changes: 20 additions & 0 deletions test/rules/only-arrow-functions/allow-declarations/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function foo(a: any) : any {
return;
}

let a = () => {};
let b = function () {};
~~~~~~~~ [0]

function c() {}

function () {
// ...
}

((func) => func())(function e(): void {});
~~~~~~~~ [0]

((func) => func())(() => {});

[0]: non-arrow functions are forbidden
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"only-arrow-functions": [true, "allow-declarations"]
}
}