Daily Front_Minhhk

[TS] 객체, 배열, 튜플, 열거형(enum), Any, 조합 본문

Study/Typescript

[TS] 객체, 배열, 튜플, 열거형(enum), Any, 조합

Minhhk 2023. 5. 5. 16:12

1. 객체

아래와 같은 방법으로

const person : {} === const person : object

 

const person : { 키 : 타입지정 } = { 키 : 값 } 
변수명 : { 안에서 구분할땐 , 가 아니라 ; 사용!! }

 

const person: {
  name: string;
  age: number;
} = {
  name: "Maximilian",
  age: 30,
};

console.log(person.age);

 

 

2. 중첩객체

 

js

const product = {
  id: 'abc1',
  price: 12.99,
  tags: ['great-offer', 'hot-and-new'],
  details: {
    title: 'Red Carpet',
    description: 'A great carpet - almost brand-new!'
  }
}

 

>>

객체의 타입

 

{
  id: string;
  price: number;
  tags: string[];
  details: {
    title: string;
    description: string;
  }
}

 

... 객체 타입 안에 객체 타입이 있다고 말할 수 있다.

 

 


 

3. 배열

string 만 있을 땐 -> string[]

number, string 일 땐 -> (number | string)[]

 

const person: {
  name: string;
  age: number;
  hobbies: string[];
  like: (string | number)[];
  another: (string | number | boolean)[];
} = {
  name: "Maximilian",
  age: 30,
  hobbies: ["Sports", "Cooking"],
  like: [7, "computer"],
  another: [1, 2, "3", true],
};

 

 


4. 튜플 - 길이와 타입이 고정된 배열

 

role 키의 값에 number와 string 둘 다 넣고 싶을 땐,
대괄호 안에 타입 지정
>
role : [number, string]

 

const person: {
  name: string;
  age: number;
  hobbies: string[];
  role: [number, string];
} = {
  name: 'Maximilian',
  age: 30,
  hobbies: ['Sports', 'Cooking'],
  role: [2, 'author']
};

 

만약

role : [number, string] 인데
role[0] 에 string 타입이 들어간다면

에러 발생

그리고

role : [number, string] 인데

객체 값에

role : [2, "abc", "def"]

3개의 값이 들어가도 에러!!

 

 

 


 

5. 열거형 (enum) - 식별자들을 중괄호 쌍 안에 넣는 방식 // enum {NEW, OLD}

enum Role { admin, user, author}

->

admin 은 0번 ,, Role.admin = 0

user 은 1번 ,, Role.user = 1

author 은 2번 ,, Role.author = 2

 

 

또한 숫자 지정이나, 스트링을 지정 할 수 있음

enum Role { ADMIN = 'ADMIN', READ_ONLY = 100, AUTHOR = 'AUTHOR' };

 

=>

식별자가 필요할 때 좋다👍🏻

 

 


 

6. Any ,, *

아무타입이나 쓸 수있지만,, 타입스크립트를 쓰는 장점이 사라진다!

 

let array1 : any[]
favoriteActivities = 'sports'

->

 

any[] ,,

스트링안의 아무 타입이 와도 상관없음

 

array 규칙만 지키자!

 

=>

let array1 : any[]
array1 = ['sports',1,4,false]

 

 


 

7. 조합 (union)

매개변수에 number | string 타입 지정하여, 조건문을 통해 입력되는 타입에 따라 정확한 결과 도출

 

union type 사용 시 매개변수를 보다 유연하게 사용 가능!
function combine(input1: number | string, input2: number | string) {
  let result;
  if (typeof input1 === 'number' && typeof input2 === 'number') {
    result = input1 + input2;
  } else {
    result = input1.toString() + input2.toString();
  }
  return result;
}

const combinedAges = combine(30, 26);
console.log(combinedAges);

const combinedNames = combine('Max', 'Anna');
console.log(combinedNames);