Typescript 분석하기(1) - Parital, Required, Readonly, Pick, Record

Yechan Jung·2024년 8월 7일

이 글은 "타입스크립트 교과서(길벗)"의 3장 내용을 참고로 만들었음을 밝힌다.

Partial<Type>

기존 객체의 속성을 전부 optional로 만든다.

// Partial

type MyPartial<T> = {
  [P in keyof T]?: T[P];
};

type MyPartialResult = MyPartial<{ a: string; b: number }>;

// type MyPartialResult = {
//   a?: string | undefined;
//   b?: number | undefined;
// }

Required<Type>

Partial과 반대로 모든 속성을 옵셔녈이 아니게 만든다.

// Required

type MyRequired<T> = {
  [P in keyof T]-?: T[P];
};

type MyRequiredResult = MyRequired<{ a?: string; b?: number }>;

// type MyRequiredResult = {
//   a: string;
//   b: number;
// }

Readonly<Type>

모든 속성을 readonly로 만듭니다.

// Readonly

type MyReadonly<T> = {
  readonly [P in keyof T]: T[P];
};

type MyReadonlyResult = MyReadonly<{ a: string; b: number }>;

// type MyReadonlyResult = {
//   readonly a: string;
//   readonly b: number;
// }

모든 속성을 readonly가 아니게 만들려면 -readonly를 대신 적으면 됩니다.

// NotReadonly

type MyNotReadonly<T> = {
  -readonly [P in keyof T]: T[P];
}

type MyNotReadonlyResult = MyNotReadonly<readonly string[]>;

// type MyNotReadonlyResult = string[]

Pick<Type, Keys>

객체에서 지정한 속성만 추리는 타입입니다.

// Pick

type MyPick<T, K extends keyof T> = {
  [P in K]: T[P];
};

type MyPickResult = MyPick<{ a: string; b: number; c: boolean }, "a" | "c">;

// type MyPickResult = {
//   a: string;
//   c: boolean;
// }

객체의 속성이 아닌 경우는 무시하고, 나머지 속성만 추리게 하려면?

// Pick2

type MyPick2<T, K> = {
  [P in K extends keyof T ? K : never]: T[P];
};

type MyPick2Result = MyPick2<
  { a: string; b: number; c: boolean },
  "a" | "c" | "d"
>;
// type MyPick2Result = {
//   a: string;
//   c: boolean;
// }

type UndesiredPick2Result = MyPick2<{ a: string; b: number; c: boolean }, "d">;
// type UndesiredPick2Result = {}

하지만 이 방식은 UndesiredPick2Result 처럼 타입이 {}이 되어버릴 수 있다.
({}타입은 객체가 아닌 null 과 undefined를 제외한 모든 값)

Record<Keys, Type>

모든 속성이 타입이 동일한 객체의 타입이다.

// Record

type MyRecord<K extends keyof any, T> = {
  [P in K]: T;
};

type MyRecordResult = MyRecord<"a" | "b", string>;

// type MyRecordResult = {
//   a: string;
//   b: string;
// 

출처 : https://www.typescriptlang.org/docs/handbook/utility-types.html

profile
꿈꾸는 개발자

0개의 댓글