티스토리 뷰
타입스크립트에서의 배열은 다음과 같이 정의할 수 있다.
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 속성이 특정 구조를 가진 객체임을 나타낸다.
'Client > TypeScript' 카테고리의 다른 글
[TypeScript] in 문법, typeof 문법 차이 (0) | 2024.06.01 |
---|---|
[TypeScript] keyof & typeof 연산자 (0) | 2024.05.31 |
[TypeScript] 인덱스 시그니쳐 (0) | 2024.05.27 |
[TypeScript] TypeScript에서 클래스(Class) 사용하기 (0) | 2024.05.25 |
[TypeScript] any 타입과 unknown 타입의 차이점 (0) | 2024.05.23 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- innerhtml
- arguments
- 비동기
- 스프린트프론트엔드6기
- html
- 제어 컴포넌트
- Next.js
- 유사배열객체
- 프론트엔드
- 객체
- 동기
- Target
- 배열
- rest parameter
- map
- 코드잇 스프린트
- CSS
- GitHub
- 리액트
- hydrationboundary
- Git
- 코드잇스프린트
- 취업까지달린다
- currentTarget
- js
- tanstackquery
- 비제어 컴포넌트
- javascript
- 중급 프로젝트
- react
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함