| 배열과 튜플
배열
배열 정의 두가지방법이 있음
// 배열 타입
//첫번째방법 : []사용
const arr1: number[] = [1, 2, 3];
const arr2: string[] = ["hi", "hello", "world"];
//두번째방법 : 제네릭타입
const arr3: Array<number> = [1, 2, 3];
const arr4: Array<string> = ["hi", "hello", "world"];
cont arr = [1, true, false, "haha", {}];
이런식으로는 거의 안씀
실제로는 아래 형식으로 많이 사용
const arr5 = [
{
name: "jae",
age:25,
city: "seoul",
},
{
name: "park",
age:21,
city: "seoul",
},
{
name: "lee",
age:26,
city: "busan",
},
]
인터페이스를 사용한다면
interface IPerson{
name: string;
age: number;
city?: string;
}
const arr5: IPerson[] = [
{
name: "jae",
age:25,
},
{
name: "park",
age:21,
city: "seoul",
},
{
name: "lee",
age:26,
city: "busan",
},
{
name: "shin",
age:24,
city: "cheonan",
},
]
arr5.forEach((e: IPerson) -> console.log(e?.city ?? "default"));
튜플
배열의 길이 length 와 안에 원소를 바꿀수 없다 => 불변성유지
const arr6: [number, string, object, any[]] = [1, "hi", {},[]];
console.log(arr6);
arr6.push("hahaha");
console.log(arr6);
하지만 push 한 결과를 보니 hahaha가 들어간다
이는 논리적인 자료구조라서 그렇다
나중에 함수형 프로그래밍 할때 다시 다루겠다
지금은 이런게 있다 정도만 알고있자.
반응형
'웹 개발 > #️⃣ TypeScript' 카테고리의 다른 글
TS | 함수 타입과 type (0) | 2023.05.30 |
---|---|
TS | enum과 literal (0) | 2023.05.30 |
TS | 인터페이스 (0) | 2023.05.29 |
TS | 타입 주석과 추론 (1) | 2023.05.29 |
TS | 설치 및 실행법 (0) | 2023.05.29 |