Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The += (addition assignment) operator evaluates the addition or string concatenation of the right operand and the current value of the left operand, subsequently assigning the evaluated result back to the left operand.
leftOperand += rightOperand;
While conceptually similar to the expanded assignment expression leftOperand = leftOperand + rightOperand, the += operator evaluates the leftOperand exactly once. This distinction is critical when the left operand contains side effects (such as an incrementing index or a getter method). In an expression like arr[i++] += 5, the index i is evaluated and incremented only once, whereas the expanded form arr[i++] = arr[i++] + 5 would evaluate the increment operation twice, yielding a completely different result.

Type Resolution and Behavior

In TypeScript, the behavior of the += operator is dictated by the types of the operands. The TypeScript compiler (tsc) enforces strict type checking during this operation to prevent implicit type coercion anomalies common in standard JavaScript.
  1. Numeric Addition: If both operands are strictly of type number, or if both operands are strictly of type bigint, the operator performs standard mathematical addition. TypeScript strictly prohibits mixing number and bigint in the same operation.
  2. String Concatenation: If either the left or right operand is of type string, the operator performs string concatenation.
  3. Type Assignability: TypeScript verifies that the return type of the evaluated expression is assignable to the declared type of the leftOperand. If it is not, the compiler emits a type error.

Syntax Visualization

Evaluation Semantics:
let i = 0;
const arr = [10, 20];
arr[i++] += 5; 
// 'i' is evaluated and incremented only once. arr[0] becomes 15.
Valid Numeric Assignment:
let numericValue: number = 10;
numericValue += 5; // Evaluates to 15. Type remains 'number'.

let bigIntValue: bigint = 10n;
bigIntValue += 5n; // Evaluates to 15n. Type remains 'bigint'.
Valid String Concatenation:
let stringValue: string = "foo";
stringValue += "bar"; // Evaluates to "foobar". Type remains 'string'.
Compiler Error (Mixing BigInt and Number):
let numericBase: number = 10;
numericBase += 5n;
// TS Compiler Error: Operator '+=' cannot be applied to types 'number' and 'bigint'.
Compiler Error (Type Assignability Mismatch):
let strictNumber: number = 10;
strictNumber += "5"; 
// TS Compiler Error: Type 'string' is not assignable to type 'number'.
// (10 + "5" evaluates to the string "105", which cannot be assigned back to a number).
Master TypeScript with Deep Grasping Methodology!Learn More