TypeScript, 복잡한 중첩 객체 타입의 모든 중첩 키를 유니언 타입으로 추출

다음과 같은 복잡한 중첩 객체의 타입이 존재합니다.

// 테스트용 인터페이스
interface UserProfile {
  id: number;
  user: {
    name: string;
    address: {
      city: string;
      zipCode: number;
    };
  };
}

상기 중첩 객체 타입의 모든 키들을 유니언 타입으로 추출하면 그 결과는 다음과 같이 구성할 수 있습니다.

type UserPaths = DeepKeys<UserProfile>;
// 결과: "id" | "user" | "user.name" | "user.address" | "user.address.city" | "user.address.zipCode"

이런 결과를 만들어 주는 DeepKeys의 구현 코드는 다음과 같습니다.

type DeepKeys<T> = T extends object
  ? {
    [K in keyof T & (string | number)]: T[K] extends object
    ? `${K}` | `${K}.${DeepKeys<T[K]>}`
    : `${K}`;
  }[keyof T & (string | number)]
  : never;

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다