티스토리 뷰

 

 

타입스크립트에서의 배열은 다음과 같이 정의할 수 있다.

let numArr: number[] = [1, 2, 3]

 

 

 

 

문자열 배열 타입 정의


만약 문자열을 담는 배열의 타입을 정의한다면 다음과 같이 하면 된다.

let strArr: string[] = ["hello", "im", "winterlood"];

 

 

 

 

객체 배열 타입 정의


객체를 담는 배열을 정의할 수 도 있다. 예시로 다음과 같은 객체 배열이 있다고 해보자.

type Post = {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
    age: number;
  };
};

let posts: Post[] = [
  {
    title: "첫 번째 게시글",
    content: "첫 번째 게시글의 내용",
    author: {
      id: 1,
      name: "Alice",
      age: 30,
    },
  },
  {
    title: "두 번째 게시글",
    content: "두 번째 게시글의 내용",
    author: {
      id: 2,
      name: "Bob",
      age: 25,
    },
  },
];

 

 

 

 

배열 요소 타입에 접근하기


배열의 각 요소 타입에 접근하려면 다음과 같이 작성할 수 있다.

type PostList = {
  title: string;
  content: string;
  author: {
    id: number;
    name: string;
    age: number;
  };
}[];

// 배열 타입을 가진 PostList 정의
const posts: PostList = [
  {
    title: "첫 번째 게시글",
    content: "첫 번째 게시글의 내용",
    author: {
      id: 1,
      name: "Alice",
      age: 30
    }
  },
  {
    title: "두 번째 게시글",
    content: "두 번째 게시글의 내용",
    author: {
      id: 2,
      name: "Bob",
      age: 25
    }
  }
];

// PostList 배열의 요소 타입 정의
const post: PostList[number] = {
  title: "새 게시글",
  content: "새 게시글의 내용",
  author: {
    id: 3,
    name: "Charlie",
    age: 35
  }
};

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

// 사용 예시
printAuthorInfo(post.author); // Charlie-3

PostList 타입은 여러 개의 포스트 객체를 담을 수 있는 배열 타입을 정의한다.

PostList[number]는 PostList 배열의 요소 타입을 의미한다. 이는 배열 내의 각 요소가 특정 구조를 가진 객체임을 나타낸다.

PostList[number]["author"]는 각 요소의 author 속성 타입을 의미한다. 이는 author 속성이 특정 구조를 가진 객체임을 나타낸다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함