타입스크립트의 연산자

타입스크립트의 연산자

이 글은 타입스크립트의 연산자에 대해 설명합니다.

YouTube Video

타입스크립트의 연산자

타입스크립트에서 연산자는 숫자 계산, 값 비교 및 논리 작업을 수행하는 데 사용됩니다. 타입스크립트는 자바스크립트와 비슷한 연산자를 사용하기 때문에 익숙해지기 쉽지만, 타입스크립트는 타입 안정성을 이용한 보다 엄격한 작업을 허용합니다.

주요 연산자는 다음과 같습니다:.

산술 연산자

산술 연산자는 숫자 계산에 사용됩니다.

연산자 설명 예제 결과
+ 덧셈 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
! 부정 (NOT) !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
^ 배타적 OR (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에서는 이러한 연산자를 사용하여 복잡한 계산과 조건식을 효율적으로 작성할 수 있습니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video