TS object, array, tuple 타입

은유로그·2022년 1월 12일
0

🗣 TypeSript

목록 보기
3/3

오늘은 타입스크립트의 object, array, tuple 타입에 대해 학습했다.

object type

// 방법 1.
const person: {
  name: string; // 콤마(,)가 아닌 세미콜론(;)으로 끝낸다.
  age: number;
} = {
  name: "eunyu", //name
  age: 27
};

// 방법 2.
const person: object = {
  name: "eunyu",
  age: 27
};

// 방법 3.
const person: {} = {
  name: "eunyu",
  age: 27
};

// 방법 4.
const person = {
  name: "eunyu",
  age: 27
};

방법 1 ~ 4 모두 person 변수를 object type으로 추론하고,
name key는 string type, age key는 number type으로 추론한다.

array type

const hobbies = ["Sports", "Cooking"];
// type: string[]

const even = [2,4,6];
// type: number[]

const arr = [1, "a", 2, "b"];
// type: any[]

요소의 타입에 따라 배열 타입이 달라진다.

만약 요소가 모두

  • string이면 string[]
  • number이면 number[]
  • string, number 둘 다 있으면 any[]

으로 쓴다.

tuple type

자바스크립트에는 없는 타입이다. 길이와 요소의 타입이 고정된 배열 타입이다.

const role = [2, "author"];
// type: (string | number) [] 또는 [number, string]
profile
๑•‿•๑

0개의 댓글