Skip to main content

restrict-plus-operands

Require both operands of addition to be the same type and be bigint, number, or string.

💭

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.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/restrict-plus-operands": "error"
}
};
Try this rule in the playground ↗

Examples

var foo = '5.5' + 5;
var foo = 1n + 1;

Options

This rule accepts the following options

type Options = [
{
/** Whether to allow `any` typed values. */
allowAny?: boolean;
/** Whether to check compound assignments such as `+=`. */
checkCompoundAssignments?: boolean;
},
];

const defaultOptions: Options = [
{ checkCompoundAssignments: false, allowAny: false },
];

checkCompoundAssignments

Examples of code for this rule with { checkCompoundAssignments: true }:

/*eslint @typescript-eslint/restrict-plus-operands: ["error", { "checkCompoundAssignments": true }]*/

let foo: string | undefined;
foo += 'some data';

let bar: string = '';
bar += 0;

allowAny

Examples of code for this rule with { allowAny: true }:

var fn = (a: any, b: boolean) => a + b;
var fn = (a: any, b: []) => a + b;
var fn = (a: any, b: {}) => a + b;

When Not To Use It

If you don't mind "[object Object]" in your strings, then you will not need this rule.

Further Reading

Resources