TypeScript | index signature (인덱스 시그니처)

앙두·2023년 8월 31일
0

TypeScript

목록 보기
1/1

사프로 열코 중에, 객체의 특정 value를 가져와야 해서 obj[key]식으로 접근했는데 TypeError가 발생! 🚨
해당 에러를 구글링 하다 Index Signature를 알게되어 공부하게 되었다.


Index Signature

기존 JavaScript에서 객체에 접근을해보자.

const obj = {
  fruit: 'watermelon',
  color: 'green',
}

obj['color'] // 'green'

특정 value에 접근하고 싶을 때, 해당 value의 key를 obj에 문자열로 인덱싱해 참조하는 방법이 바로 Index Signature다.

TypeScriptIndex Signature는 위와 같이 기존 JavaScriptIndex Signature에 대한 Type을 지정해주는 것이다.

그럼 Type을 지정해보자.

interface objType {
  [key: string]: string,
}

const obj: objType = {
  fruit: 'watermelon',
  color: 'green',
}

obj['color'] // 'green'

위와 같이 지정해주면 된다!
원래는 객체의 타입을 value별로만 지정해주었다면, index signature를 사용하면 keyvalue 둘 다 type을 지정해줄 수 있다.

만약 index signature로 type을 정해주지 않는다면, 아래와 같은 에러가 뜬다.

const obj = {
  fruit: 'watermelon',
  color: 'green',
}

obj['color'] // No index signature with a parameter of type 'string' was found on type 'obj'.

obj에서 string유형의 parameter를 찾지 못하겠다는 내용이다.


key가 숫자인 경우도 있다.

const obj = {
  1: 'hello',
  2: 'bonjour',
  3: '안녕',
}

이럴 때도 [key: string]: string으로 인덱스 시그니처를 해줄 수 있겠지만, 배열처럼 인덱스 번호로 접근하게 할 수도 있다.

interface objType {
  [index: number]: string;
}

const obj: objType = {
  1: 'hello',
  2: 'bonjour',
  3: '안녕',
}

obj[2] // 'bonjour'

key가 number형식이라면, number type으로 주는게 아무래도 직관적이다.


만약 key 속성들이 숫자도 있고 문자열도 있다면?

interface objType {
  [index: number]: string;
  [key: string]: string;
}

const obj: objType = {
  1: 'hello',
  color: 'green',
  2: 'bonjour',
  fruit: 'watermelon',
  3: '안녕',
}

obj[2] // 'bonjour'
obj['fruit'] // 'watermelon'

2가지 방법 다 index signature로 설정해주면, 인덱스 번호나 문자열로 둘 다 접근이 가능해진다!

Index Signature는 언제 사용하면 좋을까?

  • 객체의 특정 value에 접근하고 싶을 때

  • 객체의 속성들(key, value)의 모든 이름이나 type을 명확히 알지 못할 때, 속성의 type만 우선 지정해주어 객체의 정보들에 접근하기 위해 사용
    ( 반드시, 속성(key)의 type은 string 혹은 number 여야만 한다. )

  • 속성의 type을 알고있는 상황이라면, 정확한 type을 정의하여 실수를 방지

profile
쓸모있는 기술자

0개의 댓글