Skip to content

Commit

Permalink
Adding "allow-declarations" to only-arrow-functions (palantir#1452)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Goldberg authored and Nina Hartmann committed Aug 31, 2016
1 parent 7f5360e commit c4686d7
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 4 deletions.
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"]
}
}
File renamed without changes.

0 comments on commit c4686d7

Please sign in to comment.