Skip to content

Commit

Permalink
fix(eslint-plugin): restrict-plus-operands: generic constraint support (
Browse files Browse the repository at this point in the history
  • Loading branch information
bradzacher authored and JamesHenry committed Apr 24, 2019
1 parent 92e65ec commit 3f305b1
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 3 deletions.
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,
},
],
},
],
});

0 comments on commit 3f305b1

Please sign in to comment.