[한입] 인덱스드 엑세스 타입

TK·2023년 12월 18일
0

[강의] 한입 시리즈

목록 보기
48/59

인덱스드 엑세스 타입

(Indexed Access Type)

객체, 배열, 튜플 타입에서 특정 프로퍼티 혹은 요소의 타입을 추출하는 타입


✏️객체 타입

  • 일반적으로 작성된 코드
interface Post {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}

function printAuthorInfo(author: { id: number; name: string }) {
  console.log(`${author.name} - ${author.id}`);
}

const post: Post = {
  title: "게시글 제목",
  content: "게시글 컨텐츠",
  author: {
    id: 1,
    name: "이정환",
  },
};

  • 여기서 만약 author의 프로퍼티값 location이 추가 되면 (예를들면) author의 값을 받는 모든 함수들에 그 값을 일일히 추가해주어야 한다. (번거로움)

  • 인덱스드 엑세스를 사용하면 다음 코드와 같다.
interface Post {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}

function printAuthorInfo(author: Post["author"]) { // 👈
  console.log(`${author.name} - ${author.id}`);
}

const post: Post = {
  title: "게시글 제목",
  content: "게시글 컨텐츠",
  author: {
    id: 1,
    name: "이정환",
  },
};

  • 프로퍼티의 타입이 추가되거나 수정되어도 즉시 반영된다.

※ 용어: 인덱스(index) ※


  • 주의사항1: 인덱스에 들어가는 문자열은 값이 아니라 타입이다.
    • 다음과 같이 작성하면 오류가 발생한다.
// ...생략

const key = "author";

function printAuthorInfo(author: Post[key]) { // ❌오류 (변수이자 값 →불가)
  console.log(`${author.name} - ${author.id}`);
}

  • 주의사항2: 프로퍼티에 없는 값이 들어가면 오류가 발생한다.
interface Post {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}

function printAuthorInfo(author: Post["what"]) { // ❌오류
  console.log(`${author.name} - ${author.id}`);
}

참고: author에서 id 값만 가져오고 싶은 경우

  • 이중 대괄호[]를 사용한다.
interface Post {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}
function printAuthorInfo(author: Post["author"]["id"]) { // 👈
  console.log(`${author.name} - ${author.id}`);
}
  • 아래와 같이 authornumber타입으로 지정됨

✏️배열 타입

  • 배열 타입은 인터페이스가 아닌 타입별칭으로 한다.
type PostList = { // 👈1.타입별칭
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}[]; // 👈2.배열

function printAuthorInfo(author: PostList[number]["author"]) { // 👈3.별첨
  console.log(`${author.name} - ${author.id}`);
}

const post: PostList[number] = { // 👈4.별첨
  title: "게시글 제목",
  content: "게시글 컨텐츠",
  author: {
    id: 1,
    name: "이정환",
  },
};
  • 별첨3. 요소의 타입을 먼저 뽑고 그 객체타입으로부터 author프로퍼티 타입을 뽑아온다.
  • 별첨4. number를 넣으면 배열타입으로부터 하나의 배열타입만 가져온다
    • 숫자를 넣어도 된다
const post: PostList[0] = { // 👈
  title: "게시글 제목",
  content: "게시글 컨텐츠",
  author: {
    id: 1,
    name: "이정환",
  },
};

✏️튜플 타입

  • 튜플타입은 다음과 같이 사용한다.
type Tup = [number, string, boolean];

type Tup0 = Tup[0];
type Tup1 = Tup[1];
type Tup2 = Tup[2];
type Tup3 = Tup[3]; // ❌오류 → 길이고정
type TupNum = Tup[number]; // 👈number
// → 튜플타입 안에 있는 모든 타입의 최적의 공통타입을 추론
profile
쉬운게 좋은 FE개발자😺

0개의 댓글