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

[bug-fix] no-invalid-this / ignore functions w "this" param #3267

Merged
merged 4 commits into from Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/rules/noInvalidThisRule.ts
Expand Up @@ -15,9 +15,9 @@
* limitations under the License.
*/

import { isThisParameter } from "tsutils";
import * as ts from "typescript";

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

const OPTION_FUNCTION_IN_METHOD = "check-function-in-method";
const DEPRECATED_OPTION_FUNCTION_IN_METHOD = "no-this-in-function-in-method";
Expand Down Expand Up @@ -47,7 +47,7 @@ export class Rule extends Lint.Rules.AbstractRule {
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_STRING_OUTSIDE = "the \"this\" keyword is disallowed outside of a class body" ;
public static FAILURE_STRING_OUTSIDE = "the \"this\" keyword is disallowed outside of a class body";
public static FAILURE_STRING_INSIDE = "the \"this\" keyword is disallowed in function bodies inside class methods, " +
"use arrow functions instead";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
Expand Down Expand Up @@ -76,6 +76,9 @@ function walk(ctx: Lint.WalkContext<boolean>): void {

case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.FunctionExpression:
if ((node as ts.FunctionLikeDeclaration).parameters.some(isThisParameter)) {
return;
}
if (inClass) {
inFunctionInClass = true;
ts.forEachChild(node, cb);
Expand Down
18 changes: 18 additions & 0 deletions test/rules/no-invalid-this/enabled/test.ts.lint
@@ -1,3 +1,21 @@
export function f<T>(this: Observable<T>): Observable<T> {
const nestedFunction = function(this) => {
console.log(this)
}
return this.map(i=>i);
}

class ContextualThisClass {
private someMethod(): void {
let nestedFunction: (this: number[]) => number[] = function(this) {
[3,4].forEach(function(nr){
console.log(this);
});
return this.map(i=>i);
};
}
}

function foo(x: number) {
console.log(this.x);
~~~~ [the "this" keyword is disallowed outside of a class body]
Expand Down