TypeScript Operators Guide

In TypeScript, operators work similarly to JavaScript and support common mathematical operations, comparison operations, logical operations, and more. Below are some common operators:

  • Mathematical Operators: +, -, *, /, %.
  • Comparison Operators: ==, !=, ===, !==, >, >=, <, <=.
  • Logical Operators: &&, ||, !.
  • Bitwise Operators: &, |, ^, ~, <<, >>, >>>.
  • Assignment Operators: =, +=, -=, *=, /=, %, etc.
  • Increment/Decrement Operators: ++, --.

It is important to note that TypeScript supports type checking; therefore, pay attention to variable types when performing operations. For example:

let num1: number = 42;
let num2: number = 13;
let str1: string = "Hello, ";
let str2: string = "world!";
let result1: number = num1 + num2; // 55
let result2: string = str1 + str2; // "Hello, world!"
let bool1: boolean = true;
let bool2: boolean = false;
let result3: boolean = bool1 && bool2; // false
let result4: boolean = bool1 || bool2; // true
let num3: number = 0b1010; // Binary number 10
let num4: number = 0b0101; // Binary number 5
let result5: number = num3 & num4; // 0b0000, bitwise AND operation
let result6: number = num3 | num4; // 0b1111, bitwise OR operation
let result7: number = ~num3; // -11, bitwise NOT operation
let a: number = 42;
a++; // The value of a becomes 43
a--; // The value of a becomes 42

In this example, we perform operations on different variables using various operators. Please note the following points:

  • When performing mathematical operations, TypeScript automatically performs type conversion, for example, converting strings to numeric types.
  • When performing logical operations, TypeScript converts operands that are not of boolean type to boolean types before processing.
  • When performing bitwise operations, ensure that bitwise operators are only applicable to integer types.
  • When performing increment/decrement operations, ensure that the increment/decrement operators are only applicable to numeric types.