TypeScriptにおける演算子

TypeScriptにおける演算子

この記事ではTypeScriptにおける演算子について説明します。

YouTube Video

TypeScriptにおける演算子

TypeScriptにおける演算子は、数値の計算や値の比較、論理的な操作などを行うために使用されます。JavaScriptと同様の演算子が使えるため、TypeScriptの演算子も馴染みやすいですが、型安全性を活かして厳密な演算が可能です。

主な演算子は以下の通りです。

算術演算子

算術演算子は数値の計算を行うための演算子です。

演算子 説明 結果
+ 加算 5 + 3 8
- 減算 5 - 3 2
* 乗算 5 * 3 15
/ 除算 5 / 2 2.5
% 剰余(余り) 5 % 2 1
++ インクリメント(前) let x = 5; ++x 6
-- デクリメント(前) 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);

代入演算子

代入演算子は、右辺の値を左辺の変数に割り当てます。

演算子 説明 結果
= 代入 x = 10 x = 10
+= 加算して代入 x += 5 x = 15
-= 減算して代入 x -= 5 x = 5
*= 乗算して代入 x *= 2 x = 20
/= 除算して代入 x /= 2 x = 5
%= 剰余で代入 x %= 3 x = 1
1let z = 5;
2z += 3;
3console.log(z);  // Outputs: 8
4
5z *= 2;
6console.log(z);  // Outputs: 16

比較演算子

比較演算子は、値の比較を行い、trueまたはfalseを返します。

演算子 説明 結果
== 等しい(型を比較しない) 5 == "5" true
=== 厳密に等しい(型も比較) 5 === "5" false
!= 等しくない(型を比較しない) 5 != "5" false
!== 厳密に等しくない(型も比較) 5 !== "5" true
> より大きい 5 > 3 true
< より小さい 5 < 3 false
>= より大きいか等しい 5 >= 5 true
<= より小さいか等しい 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

論理演算子

論理演算子は、論理式を組み合わせる際に使用されます。

演算子 説明 結果
&& 論理積(AND) true && false false
|| 論理和(OR) true || false true
! 否定 !true false
1console.log('true && false :', true && false);  // Outputs: false
2console.log('true || false :', true || false);  // Outputs: true
3console.log('!true         :', !true);          // Outputs: false

論理演算子の優先順位

TypeScript の論理演算子は、通常は NOT が最も優先され、次に AND、最後に OR が評価されます。

NOTの優先順位が最も高い

NOTは単項演算子であり、最も優先的に評価されます。

1console.log(!true || false);  // false
ANDORより優先される

ANDOR より優先度が高いため、AND の部分が先に評価されます。

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

このように、AND (&&) の部分が先に計算され、その結果が OR (||) に渡されます。

ANDOR は短絡評価(ショートサーキット)を行う

TypeScriptの ANDOR は短絡評価(ショートサーキット)を行います。左側の値で結果が決まる場合、右側の式を評価しません。

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

このようにどちらの場合も、console.log()は実行されません。

明示的な優先順位をつける

括弧を使って明示的にグループ化することによって、優先順位の誤解を防ぐことができます。

1console.log(true || (false && false));  // true
自然言語とプログラムの解釈の違い

論理演算子を使う場合、自然言語における曖昧さにも留意する必要があります。例えば、「白い犬または猫」といった場合、「白い犬」もしくは「どんな色でもいい猫」という場合と、「白い犬」または「白い猫」という場合が考えられます。コードで書くと次のようになります。

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}

このように自然言語には曖昧さが存在するため、コーディングや設計を行う際には注意が必要です。

ビット演算子

ビット演算子は、数値をビットレベルで操作します。

演算子 説明 結果
& 論理積(AND) 5 & 1 1
` ` 論理和(OR) 5 | 1
^ 排他的論理和(XOR) 5 ^ 1 4
~ 否定(NOT) ~5 -6
<< 左シフト 5 << 1 10
>> 右シフト(符号付き) 5 >> 1 2
>>> 右シフト(符号無し) 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)

三項演算子

三項演算子は、条件式の結果によって異なる値を返します。

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

型演算子

TypeScriptの型演算子には、次のようなものがあります。

演算子 説明 結果
typeof 変数の型を返す typeof 123 "number"
instanceof オブジェクトが特定のクラスに属するかを確認する arr instanceof Array true
is 型ガードとして、値が特定の型であるかを確認する 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}

型演算子は、値の型を確認したり、特定の型に変換するために使用します。

  • typeof演算子は、変数の型を返します。
  • instanceof演算子は、オブジェクトが特定のクラスに属するかを確認します。
  • is演算子は、値が特定の型であるかを確認するために使用されます。TypeScriptの型ガードの一部です。

まとめ

  • 算術演算子: 基本的な計算を行います。
  • 代入演算子: 変数に値を代入します。
  • 比較演算子: 値の比較を行います。
  • 論理演算子: 論理的な条件を組み合わせます。
  • ビット演算子: ビット単位で演算します。
  • 三項演算子: 条件に基づいて値を返します。
  • 型演算子は値の型を確認できます。

TypeScriptでは、これらの演算子を使用して複雑な計算や条件式を効率的に書くことができます。

YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。

YouTube Video