타입스크립트 - 인덱스드 엑세스 타입

드엔트론프·2023년 8월 5일
0

typescript

목록 보기
10/12
post-thumbnail

들어가며

기본 타입이나 별칭 또는 인터페이스로 만든 원래 존재하던 타입들을 상황에 따라 유동적으로 다른 타입으로 변환하는 타입스크립트의 강력하고도 독특한 기능이다.

제네릭도 타입 조작하기 중 하나인데 내용이 방대해 따로 본 것

타입 조작하기

인덱스드 엑세스 타입

객체,배열 타입으로부터 특정 프로퍼티 타입을 쏙 뽑아 정의해주는 문법

  • Post interface가 있다고 하자.
interface Post {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}
  • 어떤 게시글에 대한 post는 아래와 같이 정의해줄 수 있을 것이다.
const post: Post = {
  title: "제목",
  content: "게시글 본문",
  author: {
    id: 1,
    name: "Kang",
  },
};
  • 그리고 이러한 post의 author를 출력해주는 함수가 있다고하자.
function printAuthorInfo(author: { id: number; name: string }) {
  console.log(`${author.name}-${author.id}`);
}
  • 기본적으로 author 매개변수의 타입을 위와같이 정의할 것이다.
  • 그런데 만약, author라는 매개변수를 받는 함수가 더 많아지고, 인터페이스 author에서 id, name 뿐만 아니라 location, phone등 계속 새로운 정보가 추가된다면?
  • 예를 들면 아래처럼 ↓ 변하는 것이다.
interface Post {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
		phone: number;
		location: string;
  };
}

const post: Post = {
  title: "제목",
  content: "게시글 본문",
  author: {
    id: 1,
    name: "Kang",
		phone: 01012341234;
		location: "Korea";
  },
};

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

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

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

printAuthorInfo(post.author)
  • 이렇게 한 번에 적어놓으니 문제없는것처럼 보이지만, 저 함수에 일일이 계속 추가해야한다면, 매우 비효율적일 것이다.
  • 이를 해결하기 위한 방법이 인덱스드 엑세스 타입이다.

printAuthorInfo 의 타입을 Post[”author"] 로 정의해준다.

  • 매개변수 author에 Post 인터페이스 author만 쏙 ~ 들어갔음을 알 수 있다.
  • 기존 인터페이스가 변해도 자동으로 따라온다.

⚠️ 주의할점.

Post[”author"] 에 “author”는 변수나 값이 아니라 타입 이다.

const key = ‘author’
function printAuthorInfo(author: Post[key]) 

와 같이 작성하면 에러가 발생한다!

💡 꿀팁

Post[”author”][”id”] 라고 작성하면 author 에 id만 가져올 수 있다!

  • 배열 타입을 가져오는 방식은 사뭇 다르게 느껴질 수 있다.
  • 먼저 정의해둔 인터페이스 Post를 타입별칭으로 바꿔주었다. 배열 내 객체의 형태로 구현.
type PostList = {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
  };
}[];

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

const post: PostList[number] = {
  title: "제목",
  content: "게시글 본문",
  author: {
    id: 1,
    name: "Kang",
  },
};

printAuthorInfo(post.author);
  • 그리고 post를 보자 . PostList[number] ? 대괄호에 number라니..?

  • 이렇게 쓰면 문제 없이 된다.. 더 신기한 건 PostList[0] 과 같이 어떤 숫자를 넣어도 정상적으로 동작한다는 점.

  • function printAuthorInfo(author: PostList[number]["author"]) 에서도 매개변수의 타입을 [number] 이후 [”author”] 를 지정해줌을 알 수 있다.

    • 위 설명처럼 number를 0처럼 숫자를 넣어도 된다.
  • 튜플의 인덱스드 액세스는 별 거 없다.

    //튜플 인덱스드 엑세스 타입
    type Tup = [number, string, boolean]
    
    type Tup0 = Tup[0];
    type Tup1 = Tup[1];
    type Tup2 = Tup[2];
    
    //최적의 공통타입 추출
    type TupNum = Tup[number];
  • 한가지 특이한 건 Tup[number]를 적으면 정의한 튜플에서 가장 최적의 공통 타입을 추출한다는 점이다.
profile
왜? 를 깊게 고민하고 해결하는 사람이 되고 싶은 개발자

0개의 댓글