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 the exponentiation operator in TypeScript, evaluating to the result of raising the left operand (base) to the power of the right operand (exponent). While mathematically equivalent to Math.pow(), the ** operator natively supports both number and bigint operands. In contrast, Math.pow() strictly accepts number types; passing a bigint to Math.pow() results in a TypeScript compile-time error (Argument of type 'bigint' is not assignable to parameter of type 'number').
base ** exponent

Type Constraints and BigInt Behavior

TypeScript enforces strict type checking on the operands. Both the base and the exponent must be of type number or bigint, and both operands must be of the exact same type. Mixing types will result in a compiler error. Furthermore, when using bigint operands, the exponent must be non-negative. Because the bigint type cannot represent fractional values, evaluating a bigint base with a negative bigint exponent throws a runtime RangeError.
const num: number = 3 ** 4;       // Valid: 81
const big: bigint = 2n ** 64n;    // Valid: 18446744073709551616n

// @ts-expect-error: Operator '**' cannot be applied to types 'bigint' and 'number'.
const mixed = 2n ** 3;            

// Compiles successfully, but throws a runtime RangeError: BigInt negative exponent
const negativeBigIntExponent = 2n ** -1n;

Associativity

Unlike most binary operators in TypeScript (which are left-associative), the ** operator is right-associative. Multiple exponentiation operations in a single expression are evaluated from right to left.
const result = 2 ** 3 ** 2;

// Evaluates as: 2 ** (3 ** 2) -> 2 ** 9 -> 512
// NOT as: (2 ** 3) ** 2 -> 8 ** 2 -> 64

Precedence and Unary Operators

The ** operator has a higher precedence than standard arithmetic operators (*, /, +, -). However, TypeScript enforces a strict parsing rule: a unary operator (such as -, +, ~, !) cannot immediately precede the base operand of an unparenthesized exponentiation expression. This prevents ambiguity regarding whether the unary operator applies to the base or the evaluated result.
// TS SyntaxError: Unary operator used immediately before exponentiation expression.
// const invalid = -2 ** 2; 

// Valid: Unary operator applied to the base
const negativeBase = (-2) ** 2;   // Evaluates to 4

// Valid: Unary operator applied to the evaluated exponentiation expression
const negativeResult = -(2 ** 2); // Evaluates to -4

Compound Assignment

The operator includes a compound assignment variant, **=, which applies the exponentiation operation to a variable and assigns the result back to that variable.
let x: number = 5;
x **= 3; // Syntactic sugar for: x = x ** 3
// x is now 125
Master TypeScript with Deep Grasping Methodology!Learn More