Operators in TypeScript

Operators in TypeScript

This article explains operators in TypeScript.

YouTube Video

Operators in TypeScript

Operators in TypeScript are used to perform numerical calculations, value comparisons, and logical operations. Since TypeScript uses similar operators to JavaScript, they are easy to get used to, but TypeScript allows for more rigorous operations using type safety.

The main operators are as follows:.

Arithmetic Operators

Arithmetic operators are used for numerical calculations.

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2.5
% Remainder 5 % 2 1
++ Increment (prefix) let x = 5; ++x 6
-- Decrement (prefix) let x = 5; --x 4
 1let a = 10; // Initialize variable 'a' with the value 10
 2let b = 3;  // Initialize variable 'b' with the value 3
 3
 4// Perform and display arithmetic operations between 'a' and 'b'
 5console.log("Addition (a + b):      ", a + b); // 13
 6console.log("Subtraction (a - b):   ", a - b); // 7
 7console.log("Multiplication (a * b):", a * b); // 30
 8console.log("Division (a / b):      ", a / b); // 3.333...
 9console.log("Modulus (a % b):       ", a % b); // 1
10
11// Demonstrate post-increment operation on 'a'
12// Output the current value of 'a' (10), then increment
13console.log("Post-increment (a++):  ", a++);
14// Display the incremented value of 'a' (11)
15console.log("Value of 'a' after increment:", a);
16
17// Demonstrate pre-increment operation on 'a'
18// Increment 'a' first (12) then output
19console.log("Pre-increment (++a):   ", ++a);
20
21// Demonstrate post-decrement operation on 'a'
22// Output the current value of 'a' (12), then decrement
23console.log("Post-decrement (a--):  ", a--);
24// Display the decremented value of 'a' (11)
25console.log("Value of 'a' after decrement:", a);
26
27// Demonstrate pre-decrement operation on 'a'
28// Decrement 'a' first (10) then output
29console.log("Pre-decrement (--a):   ", --a);

Assignment Operators

Assignment operators assign the value on the right to the variable on the left.

Operator Description Example Result
= Assignment x = 10 x = 10
+= Add and assign x += 5 x = 15
-= Subtract and assign x -= 5 x = 5
*= Multiply and assign x *= 2 x = 20
/= Divide and assign x /= 2 x = 5
%= Remainder and assign x %= 3 x = 1
1let z = 5;
2z += 3;
3console.log(z);  // Outputs: 8
4
5z *= 2;
6console.log(z);  // Outputs: 16

Comparison Operators

Comparison operators compare values and return true or false.

Operator Description Example Result
== Equal (no type comparison) 5 == "5" true
=== Strictly equal (includes type) 5 === "5" false
!= Not equal (no type comparison) 5 != "5" false
!== Strictly not equal (includes type) 5 !== "5" true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 5 <= 3 false
1console.log('5 == "5"   :', 5 == "5");   // Outputs: true
2console.log('5 === "5"  :', 5 === "5");  // Outputs: false
3console.log('5 != "5"   :', 5 != "5");   // Outputs: false
4console.log('5 !== "5"  :', 5 !== "5");  // Outputs: true
5console.log('5 > 3      :', 5 > 3);      // Outputs: true
6console.log('5 < 3      :', 5 < 3);      // Outputs: false
7console.log('5 >= 5     :', 5 >= 5);     // Outputs: true
8console.log('5 <= 3     :', 5 <= 3);     // Outputs: false

Logical Operators

Logical operators are used to combine logical expressions.

Operator Description Example Result
&& Logical AND true && false false
|| Logical OR true || false true
! Negation !true false
1console.log('true && false :', true && false);  // Outputs: false
2console.log('true || false :', true || false);  // Outputs: true
3console.log('!true         :', !true);          // Outputs: false

Precedence of Logical Operators

In TypeScript, logical operators are usually evaluated in the order of NOT first, followed by AND, and finally OR.

NOT Has the Highest Precedence

NOT is a unary operator and is evaluated with the highest precedence.

1console.log(!true || false);  // false
AND Takes Precedence Over OR

AND has a higher precedence than OR, so the AND portion is evaluated first.

1console.log(true || false && false);  // true

As a result, the AND (&&) part is computed first, and its result is passed to OR (||).

AND and OR Perform Short-Circuit Evaluation

In TypeScript, AND and OR perform short-circuit evaluation. If the result is determined by the left-hand value, the right-hand expression is not evaluated.

1let a = false && console.log("This will not be printed");
2console.log(a);  // false
3
4let b = true || console.log("This will not be printed");
5console.log(b);  // true

In both cases, console.log() is not executed.

Explicitly Defining Precedence

Using parentheses to explicitly group expressions can prevent misunderstandings about precedence.

1console.log(true || (false && false));  // true
Differences Between Natural Language and Program Interpretation

When using logical operators, it is important to be aware of ambiguities in natural language. For example, in the phrase 'a white dog or a cat,' it could mean either 'a white dog or any cat' or 'a white dog or a white cat.'. In code, it can be written as follows:.

1if (isWhite && isDog || isCat) {
2    console.log(' "A white dog" or "a cat of any color" ');
3}
4
5if (isWhite && (isDog || isCat)) {
6    console.log(' "A white dog" or "a white cat" ');
7}

Since natural language can be ambiguous, caution is required when coding and designing systems.

Bitwise Operators

Bitwise operators manipulate numbers at the bit level.

Operator Description Example Result
& Logical AND 5 & 1 1
` ` Logical OR 5 | 1
^ Exclusive OR (XOR) 5 ^ 1 4
~ Negation (NOT) ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift (Signed) 5 >> 1 2
>>> Right Shift (Unsigned) 5 >>> 1 2
1console.log('5 & 1  :', 5 & 1);   // Outputs: 1  (AND operation)
2console.log('5 | 1  :', 5 | 1);   // Outputs: 5  (OR operation)
3console.log('5 ^ 1  :', 5 ^ 1);   // Outputs: 4  (XOR operation)
4console.log('~5     :', ~5);      // Outputs: -6 (NOT operation)
5console.log('5 << 1 :', 5 << 1);  // Outputs: 10 (Left shift operation)
6console.log('5 >> 1 :', 5 >> 1);  // Outputs: 2  (Right shift operation)
7console.log('5 >>> 1:', 5 >>> 1); // Outputs: 2  (Unsigned right shift operation)

Ternary Operator

The ternary operator returns different values based on the result of a conditional expression.

1let age = 20;
2let access = (age >= 18) ? "Allowed" : "Denied";
3console.log(access);  // Outputs: Allowed

Type Operators

TypeScript's type operators include the following:.

Operator Description Example Result
typeof Returns the type of a variable typeof 123 "number"
instanceof Checks if an object belongs to a specific class arr instanceof Array true
is As a type guard, checks if a value is of a specific type value is string true or false
 1console.log(typeof "Hello");  // "string"
 2console.log(typeof 42);       // "number"
 3
 4let arr: number[] = [1, 2, 3];
 5console.log("arr instanceof Array : ", arr instanceof Array); // true
 6
 7// Example of Type Guard
 8function isString(value: any): value is string {
 9  return typeof value === "string";
10}
11
12let value: any = "Hello";
13if (isString(value)) {
14  console.log("Value is a string:", value);  // "Value is a string: Hello"
15}

Type operators are used to check the type of a value or convert it to a specific type.

  • The typeof operator returns the type of a variable.
  • The instanceof operator checks if an object belongs to a specific class.
  • The is operator is used to check if a value is of a specific type. It is part of TypeScript's type guards.

Summary

  • Arithmetic Operators: Perform basic calculations.
  • Assignment Operators: Assign values to variables.
  • Comparison Operators: Compare values.
  • Logical Operators: Combine logical conditions.
  • Bitwise Operators: Perform operations at the bit level.
  • Ternary Operator: Returns values based on conditions.
  • Type operators can check the type of a value.

In TypeScript, these operators can be used to write complex calculations and conditional expressions efficiently.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video