[TypeScript] 타입 별칭과 인덱스 시그니처

ttining·2025년 3월 14일

타입 별칭(Type Alias)

타입을 마치 변수처럼 정의하도록 도와주는 문법

  • 중복 코드가 길어질 경우

    type User = {
      id: number;
      name: string;
      nickname: string;
      birth: string;
      bio: string;
      location: string;
    };
    
    let user: User = {
      id: 1,
      name: "띠닝",
      nickname: "ttining",
      birth: "1999.99.99",
      bio: "안녕하세요",
      location: "서울",
    };
    
    let user2: User = {
      id: 2,
      name: "앙걸",
      nickname: "mygirl",
      birth: "1999.99.99",
      bio: "안녕하세요",
      location: "서울",
    };

⚠️ 주의사항

동일한 스코프에 중복된 이름의 타입 별칭을 선언할 경우, 오류가 발생한다.


## 인덱스 시그니처 객체 타입의 정의를 더 유연하게 하도록 도와주는 문법 - 인덱스 시그니처 사용 ❌ ```tsx type CountryCodes = { Korea: string; UnitedState: string; UnitedKingdom: string; // ... };
let countryCodes = {
  Korea: "ko",
  UnitedState: "us",
  UnitedKingdom: "uk",
  // ...
};
- 인덱스 시그니처 사용 ⭕
 ```tsx
 type CountryCodes = {
   [key: string]: string;
 };

 let countryCodes: CountryCodes = {
   Korea: "ko",
   UnitedState: "us",
   UnitedKingdom: "uk",
 };

 type countryNumberCodes = {
   [key: string]: number;
 };

 let countryNumberCodes = {
   Korea: 410,
   UnitedState: 840,
   UnitedKingdom: 826,
 };
 ```
- 규칙을 위반하지 않는다면, 모든 객체를 허용하는 타입이다.
 ```tsx
 type countryNumberCodes = {
   [key: string]: number;
 };

 let countryNumberCodes: countryNumberCodes = {}; // 오류 발생 ❌
 // 아무런 프로퍼티가 없으므로, 규칙을 위반할 프로퍼티가 없다.
 ```
profile
내가 보려고 만든 벨로그 *'-'*

0개의 댓글