diff --git a/packages/eslint-plugin/src/rules/restrict-plus-operands.ts b/packages/eslint-plugin/src/rules/restrict-plus-operands.ts index 62b1b1f79ce..ef73ae7478d 100644 --- a/packages/eslint-plugin/src/rules/restrict-plus-operands.ts +++ b/packages/eslint-plugin/src/rules/restrict-plus-operands.ts @@ -9,7 +9,7 @@ export default util.createRule({ docs: { description: 'When adding two variables, operands must both be of type number or of type string.', - tslintRuleName: 'restrict-plus-operands', + tslintName: 'restrict-plus-operands', category: 'Best Practices', recommended: false, }, @@ -32,10 +32,18 @@ export default util.createRule({ /** * Helper function to get base type of node - * @param type type to be evaluated - * @returns string, number or invalid */ function getBaseTypeOfLiteralType(type: ts.Type): BaseLiteral { + const constraint = type.getConstraint(); + if ( + constraint && + // for generic types with union constraints, it will return itself from getConstraint + // so we have to guard against infinite recursion... + constraint !== type + ) { + return getBaseTypeOfLiteralType(constraint); + } + if (type.isNumberLiteral()) { return 'number'; } diff --git a/packages/eslint-plugin/tests/rules/restrict-plus-operands.test.ts b/packages/eslint-plugin/tests/rules/restrict-plus-operands.test.ts index ae4fe89af15..fdda8fe0ef4 100644 --- a/packages/eslint-plugin/tests/rules/restrict-plus-operands.test.ts +++ b/packages/eslint-plugin/tests/rules/restrict-plus-operands.test.ts @@ -60,6 +60,27 @@ var foo = ("5.5" as string) + pair.second; `const foo = 'hello' + (someBoolean ? 'a' : 'b') + (() => someBoolean ? 'c' : 'd')() + 'e';`, `const balls = true;`, `balls === true;`, + // https://github.com/typescript-eslint/typescript-eslint/issues/230 + ` +function foo(a: T) { + return a + ""; +} + `, + ` +function foo(a: T) { + return a + ""; +} + `, + ` +function foo(a: T) { + return a + 1; +} + `, + ` +function foo(a: T) { + return a + 1; +} + `, ], invalid: [ { @@ -305,5 +326,62 @@ var foo = pair + pair; }, ], }, + // https://github.com/typescript-eslint/typescript-eslint/issues/230 + { + code: ` +function foo(a: T) { + return a + 1; +} + `, + errors: [ + { + messageId: 'notStrings', + line: 3, + column: 12, + }, + ], + }, + { + code: ` +function foo(a: T) { + return a + 1; +} + `, + errors: [ + { + messageId: 'notStrings', + line: 3, + column: 12, + }, + ], + }, + { + code: ` +function foo(a: T) { + return a + ""; +} + `, + errors: [ + { + messageId: 'notStrings', + line: 3, + column: 12, + }, + ], + }, + { + code: ` +function foo(a: T) { + return a + ""; +} + `, + errors: [ + { + messageId: 'notStrings', + line: 3, + column: 12, + }, + ], + }, ], });