타입스크립트 사용기 및 연습

Hunter Joe·2025년 6월 27일
0

TS 쓰면서 의구심 + 궁금증 해소 목적으로 작성해놓음

enum vs as const

  • 상수를 목적으로 사용하기에는 tConst가 컴파일 했을 때 단순 객체이기 때문에 더 가벼움
  • enum을 사용하면 양방향 맵핑이 가능하다는 장점이 있음
// 양방향 맵핑 e.g.
enum Role {
  Admin,     // 0
  User,      // 1
  Guest,     // 2
}

console.log(Role.Admin); // 0
console.log(Role[0]);    // "Admin"

복잡한 객체 타입 선언하는법

개발 중 api 응답으로 데이터를 받다보면 이런식의 데이터가 꽤 있음

data = {
  upbit : [
    {
      "currency_pair": "KRW-BTC",
      "korean_name": "비트코인",
      "english_name": "Bitcoin",
    },
    {
      "currency_pair": "KRW-ETH",
      "korean_name": "이더리움",
      "english_name": "Ethereum",
    }
  ],
  bithumb : [
    {
      "currency_pair": "KRW-BTC",
      "korean_name": "비트코인",
      "english_name": "Bitcoin",
    },
    {
      "currency_pair": "KRW-ETH",
      "korean_name": "이더리움",
      "english_name": "Ethereum",
    }
  ]
}

구조를 보면
1. data는 객체
2. upbit,bithumb이라는 키값 존재
3. 각 upbit, bithumb이라는 키값에 객체로 된 배열이 존재

이 데이터의 타입을 한번 정의해보자

interface Data {
  [exchange: string] : 
    {
      currency_pair : string,
      korean_name : string,
      english_name : string 
    }[]
}

이렇게 하나의 타입으로도 가능하지만 아까 1,2,3으로 나눴던 단계를 가지고 세분화 해서 타입을 정의해보면?

// 3. 각 `upbit`, `bithumb`이라는 키값에 객체로 된 배열이 존재 
interface DataDetail {
	currency_pair : string,
    korean_name : string,
    english_name : string 
} 

// 2. `upbit`,`bithumb`이라는 키값 존재 
// 1. `data`는 객체 
interface Data {
	[exchange: string] : DataDetail[]
}

만약 exchange도 타입을 정의하고 싶다면? (전체 코드로 작성하겠음)

type Exchange = "upbit" | "bithumb"

interface DataDetail {
	currency_pair : string,
    korean_name : string,
    english_name : string 
} 

interface Data {
	[exchange: Exchange] : DataDetail[]
}

const data : Data = {
  upbit : [
    {
      "currency_pair": "KRW-BTC",
      "korean_name": "비트코인",
      "english_name": "Bitcoin",
    },
    {
      "currency_pair": "KRW-ETH",
      "korean_name": "이더리움",
      "english_name": "Ethereum",
    }
  ],
  bithumb : [
    {
      "currency_pair": "KRW-BTC",
      "korean_name": "비트코인",
      "english_name": "Bitcoin",
    },
    {
      "currency_pair": "KRW-ETH",
      "korean_name": "이더리움",
      "english_name": "Ethereum",
    }
  ]
}

요렇게 차근차근 타입을 정의하면 됨!

객체로부터 union type 이끌어내기

const countryCurrency = {
	KOREA : "KRW",
  	USA : "USD",
  	CANADA : "CAD",
} as const;

위 객체로부터 얻어낼 수 있는 타입은 3가지 존재

  • keyof, typeof를 통해 이끌어 낼 수 있음
  1. countryCurrency객체의 전체 타입
  2. countryCurrency객체의 Key에 해당하는 Union 타입
  3. countryCurrency객체의 Value에 해당하는 Union 타입

typeof, keyof

키워드역할예시
typeofJS 값 → 타입으로 바꿈typeof obj
keyof타입 → key 유니언 추출keyof T

1. 객체의 전체 타입

const countryCurrency = {
	KOREA : "KRW",
  	USA : "USD",
  	CANADA : "CAD",
} as const;

type CountryCurrency = typeof countryCurrency
// type CountryCurrency = {
//    readonly KOREA: "KRW";
//    readonly USA: "USD";
//    readonly CANADA: "CAD";
// }

countryCurrency객체 자체를 리터럴(readonly)로 만들어버림

2. Key값 Union 타입으로 추출

const countryCurrency = {
	KOREA : "KRW",
  	USA : "USD",
  	CANADA : "CAD",
} as const;

type KCountryCurrency = typeof keyof countryCurrency 
// type KCountryCurrency = "KOREA" | "USA" | "CANADA"

3. Value값 Union 타입으로 추출

const countryCurrency = {
	KOREA : "KRW",
  	USA : "USD",
  	CANADA : "CAD",
} as const;

type VCountryCurrency = (typeof countryCurrency)[keyof typeof countryCurrency]
// type VCountryCurrency = "KRW" | "USD" | "CAD"
profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글