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 -- operator is a unary decrement operator that subtracts exactly one from its operand. It modifies the operand in place, requiring the operand to be a valid l-value (an assignable memory location, such as a variable or object property). In TypeScript, the static type checker strictly restricts the operand to types number, bigint, or any, preventing the implicit type coercion of strings or booleans that silently occurs in standard JavaScript. The operator functions in two distinct syntactic positions, which dictate its evaluation order and the resulting value of the expression: Prefix Decrement (--x) The decrement operation occurs before the expression is evaluated. It subtracts one from the operand, updates the reference, and evaluates to the newly decremented value.
let a: number = 5;
let b: number = --a; 

// Memory state:
// a === 4 (decremented immediately)
// b === 4 (assigned the new value)
Postfix Decrement (x--) The decrement operation occurs after the expression is evaluated. It evaluates to the original value of the operand, and then subtracts one from the underlying reference.
let x: number = 5;
let y: number = x--; 

// Memory state:
// x === 4 (decremented after evaluation)
// y === 5 (assigned the original value)
TypeScript Type Constraints and Errors Because the -- operator performs an implicit reassignment (x = x - 1), TypeScript enforces strict mutability and type rules at compile time:
  1. Immutability: The operand cannot be declared with const.
  2. Type Safety: The operand must be mathematically valid. Applying it to unsupported types results in Error TS2356.
  3. Enum Assignment Restriction: Although TypeScript’s arithmetic operand check technically permits enum types (avoiding Error TS2356), applying -- to an enum variable fails during the implicit reassignment phase in TypeScript 5.0+. The decrement operation yields a widened number type, which violates strict type-checking when assigned back to the enum’s strict union type, resulting in Error TS2322.
let validNum: number = 10;
validNum--; // Valid

let validBigInt: bigint = 10n;
validBigInt--; // Valid

let invalidString: string = "10";
invalidString--; // Error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.

const immutableNum: number = 10;
immutableNum--; // Error TS2588: Cannot assign to 'immutableNum' because it is a constant.

enum Direction { Up = 1, Down = 2 }
let invalidEnum: Direction = Direction.Down;
invalidEnum--; // Error TS2322: Type 'number' is not assignable to type 'Direction'.
Master TypeScript with Deep Grasping Methodology!Learn More