Skip to content

Latest commit

 

History

History
173 lines (113 loc) · 3.18 KB

restrict-plus-operands.md

File metadata and controls

173 lines (113 loc) · 3.18 KB
description
Require both operands of addition to be the same type and be `bigint`, `number`, or `string`.

🛑 This file is source code, not the primary documentation location! 🛑

See https://typescript-eslint.io/rules/restrict-plus-operands for documentation.

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.

Examples

❌ Incorrect

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

✅ Correct

let foo = parseInt('5.5', 10) + 10;
let foo = 1n + 1n;

Options

allowAny

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

❌ Incorrect

let fn = (a: number, b: []) => a + b;
let fn = (a: string, b: []) => a + b;

✅ Correct

let fn = (a: number, b: any) => a + b;
let fn = (a: string, b: any) => a + b;

allowBoolean

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

❌ Incorrect

let fn = (a: number, b: unknown) => a + b;
let fn = (a: string, b: unknown) => a + b;

✅ Correct

let fn = (a: number, b: boolean) => a + b;
let fn = (a: string, b: boolean) => a + b;

allowNullish

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

❌ Incorrect

let fn = (a: number, b: unknown) => a + b;
let fn = (a: number, b: never) => a + b;
let fn = (a: string, b: unknown) => a + b;
let fn = (a: string, b: never) => a + b;

✅ Correct

let fn = (a: number, b: undefined) => a + b;
let fn = (a: number, b: null) => a + b;
let fn = (a: string, b: undefined) => a + b;
let fn = (a: string, b: null) => a + b;

allowNumberAndString

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

❌ Incorrect

let fn = (a: number, b: unknown) => a + b;
let fn = (a: number, b: never) => a + b;

✅ Correct

let fn = (a: number, b: string) => a + b;
let fn = (a: number, b: number | string) => a + b;

allowRegExp

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

❌ Incorrect

let fn = (a: number, b: RegExp) => a + b;

✅ Correct

let fn = (a: string, b: RegExp) => a + b;

checkCompoundAssignments

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

❌ Incorrect

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

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

✅ Correct

let foo: number = 0;
foo += 1;

let bar = '';
bar += 'test';

When Not To Use It

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

Related To

Further Reading