[TypeScript-05] 연산자, Destructuring

Comely·2025년 6월 6일

TypeScript

목록 보기
5/9

1. && 연산자를 활용한 null/undefined 처리

&& 연산자의 특별한 기능

  • falsy 값: null, undefined, NaN, false
  • 동작 원리: 첫 번째 falsy 값을 반환하거나, 모두 truthy면 마지막 값 반환
1 && null && 3          // null 반환
undefined && '안녕' && 100  // undefined 반환

실무 활용법

function printAll(strs: string | undefined) {
  if (strs && typeof strs === "string") {  
    console.log(strs);
  } 
}

// 또는 더 간단하게
if (변수 != null) {
  // null과 undefined 모두 걸러냄
}

2. in 연산자로 Object Narrowing

서로 다른 속성을 가진 객체들을 구분할 때 사용

type Fish = { swim: string };
type Bird = { fly: string };

function 함수(animal: Fish | Bird) {
  if ("swim" in animal) {
    return animal.swim;  // Fish 타입으로 narrowing
  }
  return animal.fly;     // Bird 타입으로 narrowing
}

핵심: 배타적인 속성(서로 겹치지 않는 속성)이 있어야 narrowing 가능

3. instanceof로 Class 객체 구분

클래스로 생성된 객체들을 구분할 때 사용

let 날짜 = new Date();
if (날짜 instanceof Date) {
  console.log('Date 객체입니다');
}

4. Literal Type을 활용한 Narrowing

가장 실용적인 방법으로, 각 타입에 고유한 literal 값을 부여

type Car = {
  wheel: '4개',
  color: string
}

type Bike = {
  wheel: '2개', 
  color: string
}

function 함수(x: Car | Bike) {
  if (x.wheel === '4개') {
    console.log('차량: ' + x.color);
  } else {
    console.log('바이크: ' + x.color);
  }
}

장점: 비슷한 구조의 객체들도 쉽게 구분 가능


Rest 파라미터 & Destructuring

Rest 파라미터 기본 개념

개수가 정해지지 않은 파라미터를 받을 때 사용

function 전부더하기(...a: number[]) {
  console.log(a);  // 배열로 받아짐
}

전부더하기(1, 2, 3, 4, 5);  // [1, 2, 3, 4, 5]

주의사항:

  • 다른 파라미터 뒤에만 올 수 있음
  • 항상 배열 형태로 전달됨

Spread vs Rest 구분

// Spread: 배열/객체 펼치기
let arr = [3, 4, 5];
let arr2 = [1, 2, ...arr];  // [1, 2, 3, 4, 5]

// Rest: 파라미터 여러 개 받기  
function func(...params) { }

Destructuring 문법

객체 Destructuring

let { student, age } = { student: true, age: 20 };

배열 Destructuring

let [a, b] = ['안녕', 100];

함수 파라미터에서 Destructuring

// 객체 파라미터
type UserType = {
  user: string,
  comment: number[],
  admin: boolean
}

function 함수({user, comment, admin}: UserType): void {
  console.log(user, comment, admin);
}

// 배열 파라미터
type 어레이 = (number | string | boolean)[];

function 함수2([a, b, c]: 어레이) {
  console.log(a, b, c);
}

Never Type 완벽 이해

Never Type 기본 조건

함수에 never 타입을 사용하려면:
1. 절대 return하지 않음
2. 함수 실행이 끝나지 않음 (endpoint가 없음)

Never Type 사용 예시

무한 루프

function 함수(): never {
  while (true) {
    console.log(123);
  }
}

에러 발생

function 함수(): never {
  throw new Error('에러메세지');
}

Never가 자동으로 나타나는 경우

1. 잘못된 Narrowing

function 함수(parameter: string) {
  if (typeof parameter === "string") {
    parameter + 1;
  } else {
    parameter;  // never 타입이 됨 (있을 수 없는 경우)
  }
}

2. 함수 표현식 vs 함수 선언문

// 함수 선언문 → void 타입
function 함수1() {
  throw new Error();
}

// 함수 표현식 → never 타입  
let 함수2 = function() {
  throw new Error();
}

3. Strict 모드에서 빈 배열

let arr = [];  // strict 모드에서 never[] 타입

실무에서는?

Never 타입은 직접 사용할 일이 거의 없음. 주로 코드 오류 감지용으로 자동 등장하므로, never가 보이면 코드를 점검해봅시다.

profile
App, Web Developer

0개의 댓글