[Typescript] 인덱스 시그니처

Narcoker·2025년 3월 17일

Typescript

목록 보기
2/15

인덱스 시그니처

key와 value의 규칙을 기준으로 객체의 type을 정의할 수 있는 문법

Key는 각 국가의 이름이고 value는 그 국가의 두 자리 영문 코드인 객체가 있다고 가정

만약 글로벌 시스템인 경우, 국가 정의는 수백 개로 늘어날 수도 있다.

type CountryCodes = {
	Korea: string;
	UnitedState: string;
	UnitedKingdom: string;
	...
}

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

규칙을 찾을 수 있는데 키는 string, 값도 string이다.

즉 키가 string이고 값도 string인 속성들을 다음과 같이 모두 허용해주면 된다.

// 인덱스 시그니처
type CountryCodes = {
	[key: string] : string;
}

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

let emptyCodes: CountryCodes = {}

인덱스 시그니처는 아무런 프로퍼티가 없어도 오류를 발생시키지 않는다.

객체 내 반드시 필요한 속성이 있는 경우, 아래와 같이 정의할 수 있다.

단, 인덱스 프로퍼티와 규칙이 일치해야만 한다.

key의 타입이 string, value의 타입이 string인 경우,
필수 프로퍼티의 key, value도 string 이어야 한다.

type CountryCodes = {
	[key: string] : string;
	Korea: string // 규칙 일치
	// UnitedKingdom: number // 불가능
	
}

let countryCodes: CountryCodes = {
	Korea: "ko"
	...
}

출처

인프런 - 한 입 크기로 잘라먹는 타입스크립트

profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글