TypeScript Reference ยท Type Operators
TypeScript bitwise operators
Reference for bitwise operators in TypeScript: &, |, ^, ~, shifts and >>> on numbers and bigints, flag patterns and the typing rules.
Bitwise operators work on the binary representation of integers. For number operands JavaScript first converts the value to a 32-bit signed integer, applies the operation, and returns a number. For bigint operands the operation uses arbitrary-precision integers and returns a bigint.
TypeScript allows them on number, bigint, any and numeric enums, and rejects other operand types. You cannot mix number and bigint in one expression.
const flags = 0b0101; const hasFirst = (flags & 0b0001) !== 0; // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
a & b a | b a ^ b ~a a << n a >> n a >>> n a &= b a |= b a ^= b a <<= n a >>= n a >>>= n
| Operator | Description |
|---|---|
&, |, ^ |
AND, OR, XOR on each bit. |
~ |
Bitwise NOT (equals -x - 1 for numbers). |
<< |
Shift left, filling with zeros. |
>> |
Sign-propagating right shift. |
>>> |
Zero-fill right shift. Numbers only; the result is unsigned. |
Result type: number for number operands (including numeric enums), bigint for bigint operands. >>> on bigint is a runtime TypeError and a compile error.
Edge cases: shift counts are taken modulo 32 for numbers. Results above 31 bits wrap into the signed range, so 1 << 31 is -2147483648. Large values lose their high bits before the operation, as 2 ** 32 | 0 showing 0 illustrates.
Usage notes
- Operands are truncated to 32 bits. For IDs, hashes or timestamps that need more, switch to
bigint. - Precedence: comparison binds tighter than
&and|, so write(a & b) !== 0with parentheses. ~~xandx | 0truncate toward zero but only inside the 32-bit range;Math.truncis clearer and safe for large values.- Numeric enums as flags work, but TypeScript does not check that the combined value is a valid member.
- Bitwise versus logical:
&and|do not short-circuit, and&&/||work on truthiness, not bits. - Typed arrays and
DataVieware better for binary formats than manual shifting.