Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions packages/eslint-plugin/src/rules/restrict-plus-operands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand All @@ -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';
}
Expand Down
78 changes: 78 additions & 0 deletions packages/eslint-plugin/tests/rules/restrict-plus-operands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends string>(a: T) {
return a + "";
}
`,
`
function foo<T extends "a" | "b">(a: T) {
return a + "";
}
`,
`
function foo<T extends number>(a: T) {
return a + 1;
}
`,
`
function foo<T extends 1>(a: T) {
return a + 1;
}
`,
],
invalid: [
{
Expand Down Expand Up @@ -305,5 +326,62 @@ var foo = pair + pair;
},
],
},
// https://github.com/typescript-eslint/typescript-eslint/issues/230
{
code: `
function foo<T extends string>(a: T) {
return a + 1;
}
`,
errors: [
{
messageId: 'notStrings',
line: 3,
column: 12,
},
],
},
{
code: `
function foo<T extends "a" | "b">(a: T) {
return a + 1;
}
`,
errors: [
{
messageId: 'notStrings',
line: 3,
column: 12,
},
],
},
{
code: `
function foo<T extends number>(a: T) {
return a + "";
}
`,
errors: [
{
messageId: 'notStrings',
line: 3,
column: 12,
},
],
},
{
code: `
function foo<T extends 1>(a: T) {
return a + "";
}
`,
errors: [
{
messageId: 'notStrings',
line: 3,
column: 12,
},
],
},
],
});