TypeScript에서의 조건문
이 기사에서는 TypeScript에서의 조건문에 대해 설명합니다.
YouTube Video
TypeScript의 If 문
TypeScript의 if
문은 특정 조건이 true
일 경우 코드를 실행하고, 조건이 false
일 경우 실행하지 않는 분기를 수행합니다. if
문은 JavaScript와 동일한 구문을 가지며, TypeScript의 타입 안전성을 활용하여 조건부 분기를 수행합니다.
기본 구문
if
문 기본 문법은 다음과 같습니다.
1if (condition) {
2 // Code to execute if the condition is true
3} else if (anotherCondition) {
4 // Code to execute if the first condition is false
5 // and the another condition is true
6} else {
7 // Code to execute if all conditions are false
8}
condition
이true
인 경우, 다음 블록의 코드가 실행됩니다.condition
이false
이고anotherCondition
이true
인 경우, 다음 블록의 코드가 실행됩니다.- 모든 조건이
true
가 아닌 경우, 마지막else
블록의 코드가 실행됩니다.
예제 1: 기본 if-else
문
다음 예제에서는 변수 x
가 10 이상인지 확인하고 결과를 출력합니다.
1let x: number = 15;
2
3if (x >= 10) {
4 console.log("x is 10 or greater");
5} else {
6 console.log("x is less than 10");
7}
8// Outputs: x is 10 or greater
예제 2: if-else if-else
문
여러 조건을 확인하려면 else if
를 사용하여 분기를 추가하세요.
1let score: number = 85;
2
3if (score >= 90) {
4 console.log("Excellent");
5} else if (score >= 70) {
6 console.log("Passed");
7} else {
8 console.log("Failed");
9}
10// Outputs: Passed
예제 3: 타입 검사가 포함된 if
문
TypeScript의 타입 검사 기능을 사용하여 특정 타입에 대한 조건부 분기를 수행하는 것도 가능합니다. 예를 들어, typeof
연산자를 사용하여 변수의 타입을 확인하고 적절한 처리를 수행할 수 있습니다.
1let value: any = "Hello";
2
3if (typeof value === "string") {
4 console.log("The value is a string: " + value);
5} else if (typeof value === "number") {
6 console.log("The value is a number: " + value);
7} else {
8 console.log("The value is of another type");
9}
10// Outputs: "The value is a string: Hello"
예제 4: 중첩된 if
문
if
문을 중첩하여 복잡한 조건을 확인할 수도 있습니다.
1let age: number = 25;
2let isMember: boolean = true;
3
4if (age >= 18) {
5 if (isMember) {
6 console.log("You are a member and 18 years old or older");
7 } else {
8 console.log("You are not a member but 18 years old or older");
9 }
10} else {
11 console.log("You are under 18 years old");
12}
13// Output
14// You are a member and 18 years old or older
삼항 연산자 (조건부 연산자)
문법
1condition ? valueIfTrue : valueIfFalse
if
문을 더 간결하게 작성하고 싶다면, 삼항 연산자를 사용할 수 있습니다.
예제
1const number: number = 7;
2const result: string = number % 2 === 0 ? "Even" : "Odd";
3console.log(result); // "Odd"
이 경우, number
가 7
이므로 Odd
가 표시됩니다.
요약
if
문은 조건에 따라 실행할 처리를 결정하기 위한 기본적인 제어 구조입니다.else if
를 사용하여 여러 조건을 처리할 수 있습니다.typeof
를 사용하면 TypeScript의 타입을 활용하여 조건부 분기를 수행할 수 있습니다.- 중첩된
if
문을 사용하여 복잡한 조건 처리가 가능합니다. - 조건 분기를 더 간결하게 작성하기 위해 삼항 연산자를 사용할 수도 있습니다.
TypeScript에서는 타입 안전성을 고려한 if
문 사용이 코드의 신뢰성을 높일 수 있습니다.
TypeScript의 Switch 문
TypeScript의 switch
문은 여러 조건에 따라 코드를 분기하기 위해 사용하는 제어 구조입니다. if-else if
문을 사용하여 여러 조건을 평가하는 대신, switch
문을 사용하여 특정 값에 기반한 분기 로직을 간결하게 작성할 수 있습니다.
기본 구문
1switch (expressionToEvaluate) {
2 case value1:
3 // Code to execute if the expression evaluates to value1
4 break;
5 case value2:
6 // Code to execute if the expression evaluates to value2
7 break;
8 default:
9 // Code to execute if none of the conditions match
10}
switch
문에서, case
에 지정된 값이 평가된 표현식과 일치하면 case
블록이 실행됩니다. break
가 없으면 다음 case
블록이 연속적으로 실행되니 주의해야 합니다. default
블록은 어떤 case
문도 일치하지 않을 때 실행됩니다.
예제 1: 기본 switch
문
아래 예제에서는 요일을 나타내는 숫자(0부터 6까지)가 주어지고, 해당 값에 따라 대응하는 요일 이름이 출력됩니다.
1let day: number = 3;
2
3switch (day) {
4 case 0:
5 console.log("Sunday");
6 break;
7 case 1:
8 console.log("Monday");
9 break;
10 case 2:
11 console.log("Tuesday");
12 break;
13 case 3:
14 console.log("Wednesday");
15 break;
16 case 4:
17 console.log("Thursday");
18 break;
19 case 5:
20 console.log("Friday");
21 break;
22 case 6:
23 console.log("Saturday");
24 break;
25 default:
26 console.log("Invalid day");
27}
28// Outputs: Wednesday
예제 2: default
사용 예제
default
는 어떤 case
문도 일치하지 않을 때 실행되어 예상치 못한 값을 처리할 수 있어서 유용합니다.
1let statusText: string = "pending";
2
3switch (statusText) {
4 case "success":
5 console.log("Operation succeeded");
6 break;
7 case "error":
8 console.log("An error occurred");
9 break;
10 case "pending":
11 console.log("Processing");
12 break;
13 default:
14 console.log("Unknown status");
15}
16// Outputs: Processing
예제 3: 여러 case
에 대해 동일한 처리 수행하기
여러 case
문에 대해 동일한 작업을 수행하려면, 이를 연속적으로 나열할 수 있습니다.
1let fruit: string = "apple";
2
3switch (fruit) {
4 case "apple":
5 case "banana":
6 case "orange":
7 console.log("This is a fruit");
8 break;
9 default:
10 console.log("This is not a fruit");
11}
12// Outputs: This is a fruit
예제 4: break
가 생략된 경우의 동작
break
를 생략하면 다음 case
도 실행되는 "fall-through" 동작이 발생합니다.
1let rank: number = 1;
2
3switch (rank) {
4 case 1:
5 console.log("Gold");
6 case 2:
7 console.log("Silver");
8 case 3:
9 console.log("Bronze");
10 default:
11 console.log("Not ranked");
12}
13// Outputs:
14// Gold
15// Silver
16// Bronze
17// Not ranked
이런 방식으로, 하나의 case
가 일치된 후 다음 case
도 실행되므로, 불필요한 fall-through를 방지하기 위해 보통 break
를 사용합니다.
요약
switch
문은 여러 조건에 기반하여 분기 로직을 간결하게 작성할 수 있도록 도와주는 제어 구조입니다.- 각
case
는break
를 사용하여 명시적으로 프로세스를 종료해야 합니다. default
블록은 어떤case
도 일치하지 않을 때 실행됩니다.- 여러
case
에 대해 동일한 작업을 수행하는 것도 가능합니다.
TypeScript의 switch
문은 코드 가독성을 유지하면서 여러 조건을 효율적으로 처리하는 데 유용합니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.