restrict-plus-operands
Require both operands of addition to be the same type and be
bigint
,number
, orstring
.
Extending "plugin:@typescript-eslint/recommended-requiring-type-checking"
in an ESLint configuration enables this rule.
This rule requires type information to run.
TypeScript allows +
adding together two values of any type(s).
However, adding values that are not the same type and/or are not the same primitive type is often a sign of programmer error.
This rule reports when a +
operation combines two values of different types, or a type that is not bigint
, number
, or string
.
module.exports = {
"rules": {
"@typescript-eslint/restrict-plus-operands": "error"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
var foo = '5.5' + 5;
var foo = 1n + 1;
var foo = parseInt('5.5', 10) + 10;
var foo = 1n + 1n;
Options
This rule accepts an options object with the following properties:
interface Options {
/**
* Whether to check compound assignments such as `+=`.
*/
checkCompoundAssignments?: boolean;
/**
* Whether to allow `any` typed values.
*/
allowAny?: boolean;
}
const defaultOptions: Options = [
{ checkCompoundAssignments: false, allowAny: false },
];
checkCompoundAssignments
Examples of code for this rule with { checkCompoundAssignments: true }
:
- ❌ Incorrect
- ✅ Correct
/*eslint @typescript-eslint/restrict-plus-operands: ["error", { "checkCompoundAssignments": true }]*/
let foo: string | undefined;
foo += 'some data';
let bar: string = '';
bar += 0;
/*eslint @typescript-eslint/restrict-plus-operands: ["error", { "checkCompoundAssignments": true }]*/
let foo: number = 0;
foo += 1;
let bar = '';
bar += 'test';
allowAny
Examples of code for this rule with { allowAny: true }
:
- ❌ Incorrect
- ✅ Correct
var fn = (a: any, b: boolean) => a + b;
var fn = (a: any, b: []) => a + b;
var fn = (a: any, b: {}) => a + b;
var fn = (a: any, b: any) => a + b;
var fn = (a: any, b: string) => a + b;
var fn = (a: any, b: bigint) => a + b;
var fn = (a: any, b: number) => a + b;
When Not To Use It
If you don't mind "[object Object]"
in your strings, then you will not need this rule.