// TypeScript에서의 type narrowing functionprocess(value: string | number) { if (typeof value === "string") { // 이 block 내에서 value는 string type으로 처리됨 return value.toUpperCase(); } else { // 이 block 내에서 value는 number type으로 처리됨 return value.toFixed(2); } }
Ternary Operator
간단한 조건식을 한 줄로 표현할 수 있는 연산자이다.
1 2 3 4 5 6 7 8 9 10 11 12
// 기본 구문: condition ? expressionIfTrue : expressionIfFalse const age = 20; const status = age >= 18 ? "Adult" : "Minor";
functiongetArea(shape: Shape): number { switch (shape.kind) { case"circle": // 이 block에서 shape는 Circle type returnMath.PI * shape.radius ** 2; case"square": // 이 block에서 shape는 Square type return shape.sideLength ** 2; } }
TypeScript에서 조건문은 JavaScript와 동일하게 작동하지만, type system의 이점을 활용하여 더 안전하고 명확한 code를 작성할 수 있다. 특히 type guard와 discriminated union pattern을 적절히 활용하면 runtime error를 크게 줄일 수 있다.
Loop Statement
TypeScript는 JavaScript의 모든 반복문을 지원하며, type checking을 통해 더 안전한 iteration을 구현할 수 있다.
for Loop
가장 기본적인 반복문으로, 초기화, 조건, 증감식으로 구성된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 기본 for loop for (let i = 0; i < 5; i++) { console.log(i); // 0, 1, 2, 3, 4 }
// Array와 함께 사용 constnumbers: number[] = [10, 20, 30, 40, 50]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); // 10, 20, 30, 40, 50 }
// TypeScript에서는 index와 value의 type이 자동으로 추론됨 constnames: string[] = ["Kim", "Lee", "Park"]; for (let i = 0; i < names.length; i++) { // i는 number, names[i]는 string으로 추론됨 constname: string = names[i]; // type annotation 필요 없음 console.log(`${i}: ${name}`); }
// 기본 while loop let count = 0; while (count < 5) { console.log(count); // 0, 1, 2, 3, 4 count++; }
// Array 처리 constitems: string[] = ["a", "b", "c"]; let index = 0; while (index < items.length) { console.log(items[index]); // "a", "b", "c" index++; }
// TypeScript type guard와 함께 사용 functionprocessValues(values: (string | number)[]) { let i = 0; while (i < values.length) { const value = values[i]; if (typeof value === "string") { // value는 이 block에서 string으로 처리 console.log(value.toUpperCase()); } else { // value는 이 block에서 number로 처리 console.log(value.toFixed(2)); } i++; } }
TypeScript에서 반복문은 JavaScript의 모든 기능을 제공하면서도 type 안전성을 추가한다. 특히 collection 처리에서는 for...of와 Array 고차 함수를 활용하면 가독성이 높고 type-safe한 code를 작성할 수 있다. Generator와 iterator를 통해 memory 효율적인 data 처리도 가능하다.
Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Function Declaration functionadd1(a: number, b: number): number { return a + b; }
// Function Expression const add2 = function (a: number, b: number): number { return a + b; };
// Arrow Function Expression const add3 = (a: number, b: number): number => { return a + b; };
특징
함수 선언식 (Function Declaration)
함수 표현식 (Function Expression)
화살표 함수 (Arrow Function)
Hoisting
O (전체 함수가 hoisting됨)
X (변수 선언부만 hoisting, 할당은 X)
X (변수 선언부만 hoisting, 할당은 X)
this binding
호출 방식에 따라 동적으로 결정됨 (Dynamic this)
호출 방식에 따라 동적으로 결정됨 (Dynamic this)
선언될 때의 상위 scope의 this를 가짐 (Lexical this)
arguments 객체
O (함수 내에서 사용 가능)
O (함수 내에서 사용 가능)
X (상위 스코프의 arguments를 참조하거나, rest 파라미터 ...args 사용)
new 키워드 사용
O (생성자 함수로 사용 가능)
O (생성자 함수로 사용 가능, 익명 함수는 주로 X)
X (생성자 함수로 사용 불가, prototype 속성이 없음)
Method로 사용 시
this는 호출한 객체를 가리킴
this는 호출한 객체를 가리킴
this는 상위 scope를 가리키므로, 객체의 method로 사용할 때 주의 필요 (객체 literal 내에서는 객체를 가리키지 않음)
가독성 / 간결성
일반적인 함수 형태
함수를 변수에 할당하는 형태로, callback 등에 유용
구문이 간결하며, 특히 callback 함수에 유용
익명 함수 가능 여부
X (반드시 이름이 있어야 함)
O (익명 함수 가능, 변수에 할당)
O (주로 익명 형태로 사용, 변수에 할당)
주요 사용 상황
- Code의 주요 구성 block으로 명확하게 함수를 정의할 때 - 전역적으로 사용되거나, 다른 여러 곳에서 호출될 함수 - Hoisting의 이점을 활용하고 싶을 때 (함수 선언 위치에 구애받지 않고 호출) - 생성자 함수로 사용할 때 (전통적인 방식)
- 함수를 값으로 다뤄야 할 때 (변수에 할당, 객체의 속성으로 정의) - Callback 함수로 전달할 때 - Closer를 만들 때 - IIFE (즉시 실행 함수 표현식)를 사용할 때 - 조건부로 함수를 정의하거나, runtime에 함수를 선택해야 할 때
- 간결한 문법이 선호될 때 (특히 한 줄짜리 간단한 함수) - Callback 함수 내부에서 상위 scope의 this context를 유지해야 할 때 (예: setTimeout, setInterval, 배열 method forEach, map, filter 등, event handler) - 객체 literal 내에서 method를 정의할 때 this가 객체를 가리키게 하고 싶지 않을 때 (또는 lexical this가 필요할 때) - 생성자 함수로 사용하지 않을 함수, arguments 객체가 필요 없는 함수