Tslint: [no-unbound-method] False positive with Array.map and function without callback wrapper

Created on 5 Jan 2019  路  3Comments  路  Source: palantir/tslint

Bug Report

  • __TSLint version__: 5.12.0
  • __TypeScript version__: 3.2.2
  • __Running TSLint via__: CLI

TypeScript code being linted

class Some {
    private _definitions: number[] = [];

    public updateDefinition(def: number): number {
        return def * 2;
    }

    public updateDefinitions(): void {
        this._definitions = this._definitions.map(this.updateDefinition, this);
    }
}

with tslint.json configuration:

{
    "rules": {
        "no-unbound-method": true
    }
}

Actual behavior

Error for this._definitions = this._definitions.map(this.updateDefinition, this);:

ERROR: xx:xx    no-unbound-method                  Avoid referencing unbound methods which may cause unintentional scoping of 'this'.

Expected behavior

Has no errors, because I passed the context using the second argument of the .map method. Also, the call occurs within the class.

Aged Away Rule Enhancement

Most helpful comment

fixed in PR #4440

All 3 comments

fixed in PR #4440

+1 for the issue as described, but let's pause and discuss a bit before jumping to a solution. #4440 only fixes it for Array methods but doesn't fix it for similar code written by users.
The rule is also falsely complaining on the following:

function forEveryOther<T>(array: T[], method: (param: T) => void, scope?: unknown) {
    for (let i = 0; i < array.length; i += 2) {
        method.call(scope, array[i]);
    }
}

const textLogger = new TextLogger();

// Still throws an error :(
forEveryOther(["foo", "bar"], textLogger.log, textLogger);

Let's discuss to see if there's a good way the rule can avoid non-Array cases like this one.

TSLint is being deprecated (#4534) and this issue hasn't had discussion posted since the request for clarification in January. Closing this issue for housekeeping. 馃槩

Feel free to comment here if you'd like to propose a technical solution that would allow the rule to be improved!

Was this page helpful?
0 / 5 - 0 ratings