1. 개요

객체의 key, value의 type을 동적으로 정의할 때 사용하는 방법.
다음과 같이 정의한다.

interface SampleInterface {
  [key: keyType]: valueType;
}

2. 주의할 점

만약 interface 내부에 index signature와 다른 타입 정의가 혼재되어있을 경우, 각각의 타입을 서로 일치시켜야 한다.

예를 들어 다음과 같은 타입 정의는 불가능하다.

interface SampleInterface {
  [key: string]: string;
  length: number;  // Property 'length' of type 'number' is not assignable to 'string' index type 'string'.
}

반드시 interface 내부에 number 타입을 가진 length 속성을 넣고 싶은 경우, index signature를 다음과 같이 수정해야 한다.

interface SampleInterface {
  [key: string]: string | number;
  length: number;
}