TypeScript - 제네릭

김서영·2024년 2월 21일
0

제네릭

일반적인 코드를 작성하고, 이 코드를 다양한 객체에 대하여 재사용하는 프로그래밍 기법
=> 제네릭을 이용하면 클래스나 함수, 인터페이스를 다양한 타입으로 재사용 할 수 있다.
타입을 파라미터화해서 컴파일시 구체적인 타입이 결정되도록 해준다.
=> 실행시에 타입에러가 나는 거보다는 컴파일시에 미리 타입을 강하게 체크해서 에러를 사전에 방지

일반적인 함수

function getText(text) {
  return text;
}

getText('hi'); // 'hi'
getText(10); // 10
getText(true); // true

제네릭이 적용된 함수

function getText<T>(text: T): T {
  return text;
}

getText<string>('hi');
getText<number>(10);
getText<boolean>(true);

이 코드에서 getText<string>('hi')를 호출했을 때 함수는

function getText<string>(text: T): T {
  return text;
}

타입이 string이 된다!
getText() 함수를 호출할 때 제네릭(함수에서 사용할 타입) 값으로 string을 넘겼기 때문!!

유틸리티 타입

이미 정의한 타입을 변환할 때 사용하는 타입 문법

Partial< Type >

특정 타입의 부분집합을 나타내는 타입

interface Todo {
  title: string;
  description: string;
}
 
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}
 
const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};
 
const todo2 = updateTodo(todo1, {
  description: "throw out trash",
});

Required< Type >

Partial의 반대, Type 집합의 모든 프로퍼티를 필수로 설정한 타입

interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 };
Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Readonly < Type >

T의 모든 프로퍼티를 읽기 전용으로 설정하며, 해당 프로퍼티는 재할당 불가능

interface Todo {
  title: string;
}
 
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};
 
todo.title = "Hello";
Cannot assign to 'title' because it is a read-only property.

런타입에 실패할 할당 표현식을 표현할 때 유용

Record <Keys, Type>

<Key, Type>으로 Key(key):Type(value) 형태의 타입

interface PageInfo {
  title: string;
}
 
type Page = "home" | "about" | "contact";
 
const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};
 
nav.about;
const nav: Record<Page, PageInfo>

Pick< Type, Keys >

특정 타입에서 몇 개의 속성을 선택한 타입

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};
 
todo;
 
const todo: TodoPreview

Omit<Type, Keys>

T에 대한 K의 차집합(T-K)을 나타내는 타입

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};
 
todo;
 
const todo: TodoPreview
profile
개발과 지식의 성장을 즐기는 개발자

0개의 댓글

관련 채용 정보