[Typescript] 배열의 원소로 객체가 있을 때 타입 선언

박기영·2022년 7월 24일
2

Typescript

목록 보기
2/11

문제 상황

프로젝트를 진행하던 중 배열(Array)의 원소로 객체(Object)가 들어가야하는 상황이 있었다. 그 외에 string 타입도 들어가는 상황이었는데, Typescript에서는 이들의 타입을 일일이 정해줘야하므로 당혹스러웠다. 어떻게 하면 될까?

우선 필자가 만들고자 했던 배열은 아래와 같다.

[
  {
    name: "여행지",
    nameLink: "https://www.japan.travel/ko/destinations/",
    dropMenu: [
      {
        where: "도쿄",
        whereLink: "https://www.japan.travel/ko/destinations/kanto/tokyo/",
      }
    ],
    dropImg: [
      {
        img: "https://res.cloudinary.com/jnto/image/upload/w_670,h_450,c_fill,fl_lossy,f_auto/v1513913417/yamagata/Yamagata502_1",
        imgHref: "https://www.japan.travel/ko/spot/1798/",
      }
    ],
  }
]

보아하니 string 타입도 있고, object 타입도 있다.
object 타입을 명시할 때, 그 내부에 있는 key-value들을 하나씩 전부 타입 명시해준다. 여기서도 똑같다.
쉽게 생각하면 된다.

적용

// 해당 object에 대해서만 타입 정의
interface DropMenuProps {
  where: string;
  whereLink: string;
}

// 해당 object에 대해서만 타입 정의
interface DropImgProps {
  img: string;
  imgHref: string;
}

// 배열에 들어갈 원소들의 타입 정의
interface NavMenuProps {
  name: string;
  nameLink: string;
  // DropMenuProps를 타입으로 가지는 object로 이루어진 Array를 만들겠다.
  dropMenu: DropMenuProps[];
  // DropImgProps를 타입으로 가지는 object로 이루어진 Array를 만들겠다.
  dropImg: DropImgProps[];
}

이렇게 타입 정의를 했으면 배열을 생성할 때는 아래와 같이 사용한다.

// NavMenuProps를 타입으로 가지는 Array를 만들겠다.
const NavMenu: NavMenuProps[] = [
  {
    name: "여행지",
    nameLink: "https://www.japan.travel/ko/destinations/",
    dropMenu: [
      {
        where: "도쿄",
        whereLink: "https://www.japan.travel/ko/destinations/kanto/tokyo/",
      }
    ],
    dropImg: [
      {
        img: "https://res.cloudinary.com/jnto/image/upload/w_670,h_450,c_fill,fl_lossy,f_auto/v1513913417/yamagata/Yamagata502_1",
        imgHref: "https://www.japan.travel/ko/spot/1798/",
      }
    ],
  }
]

결론

필자는 Typescript를 이제 처음 써봐서, 타입 정의할 때마다 난관에 부딪친다.(useRef에 타입을 붙여줘야할 때라던지..사람들은 간단하다는데 난 어려워 죽겠다..)
그런데, 이런식으로 배열 안에 객체로 이루어진 배열이 원소로 들어간다던지 할 때는 우리가 여태까지 배워왔던 것으로 충분히 작성이 가능하다.
단순하게 생각해서, 가장 작은 타입부터 하나씩 전부 선언해나가면 된다.
배열1 > 배열2 > 객체 순서이기 때문에 객체의 타입을 먼저 전부 명시해주고, 그 객체로 배열2를 만든다고 선언해주고, 배열2로 배열1을 만들겠다고 명시해주면 된다.

참고 자료

참고 자료

profile
나를 믿는 사람들을, 실망시키지 않도록

0개의 댓글