TypeScript - 運算子
Hello, future programmers! Today, we're going to embark on an exciting journey into the world of TypeScript operators. As your friendly neighborhood computer teacher, I'm here to guide you through this adventure step by step. So, buckle up and let's dive in!
What is an Operator?
Before we start our TypeScript operator odyssey, let's understand what an operator actually is. Think of operators as special symbols that tell the computer to perform specific mathematical or logical manipulations. They're like the magic wands of programming, transforming and combining our data in various ways.
For example, when you see a "+" sign in your code, it's not just a fancy decoration. It's an operator telling the computer to add things together. Cool, right?
Arithmetic Operators
Let's kick things off with arithmetic operators. These are probably the most familiar to you, as they're similar to what you've used in math class.
Here's a table of arithmetic operators in TypeScript:
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 |
- | Subtraction | 7 - 2 |
* | Multiplication | 4 * 6 |
/ | Division | 8 / 2 |
% | Modulus (remainder) | 9 % 4 |
++ | Increment | let x = 5; x++; |
-- | Decrement | let y = 3; y--; |
Let's see these in action:
let a: number = 10;
let b: number = 5;
console.log(a + b); // Output: 15
console.log(a - b); // Output: 5
console.log(a * b); // Output: 50
console.log(a / b); // Output: 2
console.log(a % b); // Output: 0
let c: number = 7;
c++;
console.log(c); // Output: 8
let d: number = 3;
d--;
console.log(d); // Output: 2
In this example, we're performing various arithmetic operations on our variables. The modulus operator (%) might be new to some of you. It gives us the remainder after division. So, 10 % 5 is 0 because 10 divided by 5 leaves no remainder.
Relational Operators
Next up, we have relational operators. These are used to compare values and return true or false based on the comparison.
Here's a table of relational operators:
Operator | Description | Example |
---|---|---|
== | Equal to | 5 == 5 |
!= | Not equal to | 5 != 3 |
> | Greater than | 7 > 3 |
< | Less than | 2 < 8 |
>= | Greater than or equal to | 5 >= 5 |
<= | Less than or equal to | 4 <= 4 |
Let's see how these work:
let x: number = 5;
let y: number = 10;
console.log(x == y); // Output: false
console.log(x != y); // Output: true
console.log(x > y); // Output: false
console.log(x < y); // Output: true
console.log(x >= 5); // Output: true
console.log(y <= 10); // Output: true
These operators are super useful when you need to make decisions in your code based on comparing values.
Logical Operators
Logical operators are used to determine the logic between variables or values. They're like the Sherlock Holmes of programming, helping us deduce truths from multiple conditions.
Here's a table of logical operators:
Operator | Description | Example |
---|---|---|
&& | Logical AND | true && false |
|| | Logical OR | true || false |
! | Logical NOT | !true |
Let's see these in action:
let isRaining: boolean = true;
let isWarm: boolean = false;
console.log(isRaining && isWarm); // Output: false
console.log(isRaining || isWarm); // Output: true
console.log(!isRaining); // Output: false
In this example, &&
returns true only if both conditions are true. ||
returns true if at least one condition is true. !
negates the boolean value.
Bitwise Operators
Now, we're venturing into more advanced territory. Bitwise operators perform operations on binary representations of numbers. Don't worry if this sounds complex - we'll break it down!
Here's a table of bitwise operators:
Operator | Description | Example |
---|---|---|
& | Bitwise AND | 5 & 3 |
| | Bitwise OR | 5 | 3 |
^ | Bitwise XOR | 5 ^ 3 |
~ | Bitwise NOT | ~5 |
<< | Left shift | 5 << 1 |
>> | Right shift | 5 >> 1 |
Let's look at an example:
let a: number = 5; // binary: 0101
let b: number = 3; // binary: 0011
console.log(a & b); // Output: 1 (binary: 0001)
console.log(a | b); // Output: 7 (binary: 0111)
console.log(a ^ b); // Output: 6 (binary: 0110)
console.log(~a); // Output: -6 (binary: 1010 in two's complement)
console.log(a << 1); // Output: 10 (binary: 1010)
console.log(a >> 1); // Output: 2 (binary: 0010)
These operators work on the binary (base-2) representation of numbers. They're particularly useful in low-level programming and certain algorithms.
Assignment Operators
Assignment operators are used to assign values to variables. They're like the movers of the programming world, putting values into their proper homes (variables).
Here's a table of assignment operators:
Operator | Description | Example |
---|---|---|
= | Assign | x = 5 |
+= | Add and assign | x += 3 |
-= | Subtract and assign | x -= 2 |
*= | Multiply and assign | x *= 4 |
/= | Divide and assign | x /= 2 |
%= | Modulus and assign | x %= 3 |
Let's see these in action:
let x: number = 10;
x += 5; // equivalent to: x = x + 5
console.log(x); // Output: 15
x -= 3; // equivalent to: x = x - 3
console.log(x); // Output: 12
x *= 2; // equivalent to: x = x * 2
console.log(x); // Output: 24
x /= 4; // equivalent to: x = x / 4
console.log(x); // Output: 6
x %= 4; // equivalent to: x = x % 4
console.log(x); // Output: 2
These operators are shortcuts that make our code more concise and readable.
Miscellaneous Operators
TypeScript also has a few other operators that don't fit neatly into the previous categories.
Here's a table of some miscellaneous operators:
Operator | Description | Example |
---|---|---|
?: | Conditional (ternary) | condition ? expr1 : expr2 |
, | Comma | let x = (1, 2, 3) |
delete | Delete property | delete obj.property |
typeof | Type of variable | typeof x |
void | Evaluate expression and return undefined | void(0) |
Let's look at an example of the ternary operator, which is quite handy:
let age: number = 20;
let canVote: string = age >= 18 ? "Yes" : "No";
console.log(canVote); // Output: "Yes"
This is a shorthand way of writing an if-else statement. If the condition (age >= 18) is true, it returns "Yes", otherwise "No".
Type Operators
Finally, let's look at some operators specific to TypeScript that help us work with types.
Here's a table of type operators:
Operator | Description | Example |
---|---|---|
typeof | Get the type of a variable | typeof x |
instanceof | Check if an object is an instance of a class | obj instanceof Class |
as | Type assertion | (someValue as string).toUpperCase() |
Type assertion (alternative syntax) | ( |
Let's see an example:
let x: any = "Hello, TypeScript!";
let length: number = (x as string).length;
console.log(length); // Output: 20
class Animal {}
class Dog extends Animal {}
let myPet = new Dog();
console.log(myPet instanceof Animal); // Output: true
In this example, we're using type assertion to tell TypeScript that we know x
is a string, even though it's typed as any
. We're also using instanceof
to check if myPet
is an instance of the Animal
class.
And there you have it, folks! We've journeyed through the land of TypeScript operators. Remember, practice makes perfect, so don't be afraid to experiment with these operators in your own code. Happy coding!
Credits: Image by storyset