Search code examples
javascripttypescriptconcatenationeslinttypescript-eslint

Is there a way in TypeScript to warn about "1" + 1 = "11"?


JavaScript is full of caveats like this one:

const arr = [1, 2, 3]

for (const i in arr) {
  console.log(i + 1)
}

The expected by unexperienced JS developer result would be 1 2 3, but actually, it's 01 11 21.


It looks like TypeScript is not warning about concatenating strings and numbers by default, is there a way to achieve that?

To be more precise: how can I get warnings about cases like '1' + 1


Solution

  • UPDATED VALID ANSWER Use the @typescript-eslint/restrict-plus-operands rule. Both operands must either be strings or numbers, but not a mix of both:

    The eslint configuration from https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage

    {
      "parser": "@typescript-eslint/parser",
      "parserOptions": {
        "project": "./tsconfig.json"
      },
      "plugins": ["@typescript-eslint"],
      "rules": {
        "@typescript-eslint/restrict-plus-operands": "error"
      }
    }
    

    ORIGINAL

    TS Lint has the 'prefer-template' rule, though I haven't tried it with this scenario. It should work, as TypeScript sees the i variable as a string type.

    https://palantir.github.io/tslint/rules/prefer-template/

    This rule would require you to do the following to make concatenation work:

    console.log(`${i}1`);
    

    This should at least signal to the developer that they are trying to perform concatenation.

    FYI, TS Lint is being deprecated in favor of ES Lint, though I have not moved any of my projects over to that tool, yet.

    UPDATED ES Lint has the same rule: https://eslint.org/docs/rules/prefer-template