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 ++ (increment) operator is a unary mutating operator that increments its operand by a value of one. In TypeScript, the operand must be a valid l-value (such as a mutable variable or property) explicitly typed as or inferred to be number, bigint, or any.
The operator operates in two distinct syntactic positions, dictating its evaluation order relative to the return value:
Postfix Increment (operand++)
The expression evaluates to the original value of the operand before the mutation occurs. The increment operation is applied to the underlying memory reference as a side effect after the original value is yielded.
let postfixValue: number = 10;
let postfixResult: number = postfixValue++;
// postfixResult === 10 (evaluated before increment)
// postfixValue === 11 (mutated after evaluation)
Prefix Increment (++operand)
The expression mutates the operand first, and then evaluates to the newly incremented value.
let prefixValue: number = 10;
let prefixResult: number = ++prefixValue;
// prefixValue === 11 (mutated before evaluation)
// prefixResult === 11 (evaluated after increment)
TypeScript Compiler Constraints
Unlike JavaScript, which attempts implicit type coercion at runtime, TypeScript’s static type checker enforces strict constraints on the ++ operator during compilation:
- Type Safety: The operand must be assignable to a valid arithmetic type. Applying
++ to a string, boolean, or unknown yields a compile-time error.
let str: string = “5”;
str++; // Error TS2356: An arithmetic operand must be of type ‘any’, ‘number’, ‘bigint’ or an enum type.
2. **Enum Assignability:** While an `enum` is recognized as a valid arithmetic operand (avoiding `TS2356`), applying `++` to an enum variable in TypeScript 5.0+ results in an assignment error. The increment operation produces a `number`, which is no longer implicitly assignable back to a modern union enum type.
```typescript
enum Status { Pending = 1 }
let currentStatus: Status = Status.Pending;
currentStatus++; // Error TS2322: Type 'number' is not assignable to type 'Status'.
- Mutability: The operand must be a mutable reference. Applying
++ to a const variable or a readonly property results in an assignment error.
const immutableValue: number = 1;
immutableValue++; // Error TS2588: Cannot assign to ‘immutableValue’ because it is a constant.
4. **BigInt Compatibility:** When applied to a `bigint`, the operator increments the value by `1n` rather than `1`. The operand must be strictly typed as `bigint` to prevent mixed-type arithmetic errors.
```typescript
let bigValue: bigint = 100n;
bigValue++; // Evaluates to 100n, bigValue becomes 101n
Master TypeScript with Deep Grasping Methodology!Learn More