본문 바로가기

dev/typescript

typescript indexable types

타입스크립트로 사이드 프로젝트를 하던 도중, 인덱스 시그니처(Object[key]) 형태로 객체 접근 시 에러가 발생했다.

No index signature with a parameter of type 'string' was found on type ...

해결책을 찾아보니 인덱스 시그니처를 사용하려면 타입을 인덱싱 가능한 타입으로 지정해야 한다.

 

[ key : KeyType ] : PropertyType 형태로 지정이 가능하다.

이렇게 지정하면 KeyType의 키로 속성에 접근이 가능하다.

참고로 key라는 이름은 임의로 정한 것이다. 아무 이름이나 써도 무방하다.

type FormData = {
  [key: string]: string | undefined;
  username: string;
  password: string;
  passwordConfirm?: string;
};

type AuthState = {
  [key: string]: FormData; // string 타입의 key를 받아 FormData를 반환한다.
  register: FormData;
  login: FormData;
};

 

indexable type의 속성들은 모두 indexable type 규칙을 지켜야 한다.

[ key : string ] : Foo 는 속성들이 Foo 임을 나타내므로 반드시 모든 속성이 Foo 타입이어야만 한다.

type Bar = {
  [key:string] : Foo
  a : Foo // ok
  c : string // error
}

 

중첩해 사용도 가능하다.

interface NestedCSS {
  color?: string;
  nest?: {
    [selector: string]: NestedCSS;
  }
}

const example: NestedCSS = {
  color: 'red',
  nest: {
    '.subclass': {
      color: 'blue'
    }
  }
}

const failsSilently: NestedCSS = {
  colour: 'red', // TS Error: unknown property `colour`
}

 

[참조]

typescript deep dive - index signature

 

Index Signatures

 

basarat.gitbook.io

kim-macbook.log