TypeScript 활용하기: 유틸리티 타입부터 타입 가드까지

jsonLee·2023년 8월 18일
0
post-thumbnail

1. 유틸리티 타입 활용하기

1-1. Partial:

주어진 타입의 모든 프로퍼티를 선택적으로 만듭니다. 예를 들어, 특정 기능에서 Todo의 일부 필드만 업데이트하는 경우에 유용합니다.

interface Todo {
    title: string;
    description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>): Todo {
    return { ...todo, ...fieldsToUpdate };
}

const todo1 = { title: "Learn TypeScript", description: "Study advanced topics" };
const updatedTodo = updateTodo(todo1, { description: "Focus on utility types" });
console.log(updatedTodo);  // { title: 'Learn TypeScript', description: 'Focus on utility types' }

1-2. Pick:

타입에서 특정 프로퍼티만 선택할 때 사용합니다 Pick<T, K>는 타입 T에서 프로퍼티 K만 선택해서 새로운 타입을 생성합니다. 예를 들어 Todo에서 title만 가져오고 싶을 떄 사용할 수 있습니다.

//Pick<T, K>는 타입 T에서 프로퍼티 K만 선택해서 새로운 타입을 생성합니다.
type TodoPreview = Pick<Todo, 'title'>;

const todo2: TodoPreview = { title: "Learn React" };
console.log(todo2);  // { title: 'Learn React' }

1-3.Omit:

타입에서 특정 프로퍼티만 제외할 때 사용합니다. Omit<T, K>는 타입 T에서 프로퍼티 K를 제외한 나머지 프로퍼티로 새로운 타입을 생성합니다.예를 들어, description을 제외하고 싶을 때 사용할 수 있습니다.

//Omit<T, K>는 타입 T에서 프로퍼티 K를 제외한 나머지 프로퍼티로 새로운 타입을 생성합니다.
type TodoWithoutDescription = Omit<Todo, 'description'>;

const todo3: TodoWithoutDescription = { title: "Learn Vue.js" };
console.log(todo3);  // { title: 'Learn React.js' }

2. 제네릭: 리액트 컴포넌트에서 유연성 높이기

제네릭을 사용하면 다양한 타입을 유연하게 처리할 수 있습니다. 예를 들어, List 컴포넌트를 생성할 때 다양한 아이템 타입을 받아서 렌더링하고 싶다면 다음과 같이 작성할 수 있습니다.


interface ListProps<Item> {
  items: Item[];
  renderItem: (item: Item) => React.ReactNode;
}

function List<Item>({ items, renderItem }: ListProps<Item>) {
  return <ul>{items.map(renderItem)}</ul>;
}

// 사용 예:
const numbers = [1, 2, 3];
const renderNumber = (num: number) => <li key={num}>{num}</li>;
<List items={numbers} renderItem={renderNumber} />
  
  

3. 타입 가드와 타입 캐스팅

타입 가드: 특정 타입이 맞는지 확인하는 런타임 체크입니다. 예를 들어, 숫자와 문자열 중 어떤 타입이 전달되었는지 판단할 때 유용하게 사용할 수 있습니다.

function isString(value: any): value is string {
    return typeof value === 'string';
}

function printLength(value: string | number) {
    if (isString(value)) {
        console.log(`String of length: ${value.length}`);
    } else {
        console.log(`Number: ${value}`);
    }
}

printLength("Hello");  // 출력: String of length: 5
printLength(100);  // 출력: Number: 100

타입 캐스팅: 특정 DOM 요소를 가져와서 그 요소의 메서드나 프로퍼티를 사용하려면 타입 캐스팅이 필요할 때가 있습니다.

const myElement = document.getElementById('myElement') as HTMLElement;
myElement.click();

결론
타입스크립트의 고급 기능들은 코드의 안정성과 유연성을 한 단계 끌어올려줍니다.

REFERENCE

https://react-typescript-cheatsheet.netlify.app/
https://www.typescriptlang.org/ko/

profile
풀스택 개발자

0개의 댓글