Typescript
[TypeScript] String key로 객체에 접근하기
jinist
2022. 7. 26. 00:17
String타입의 키로 객체에 접근하려면
type에러가 생기는데 인덱스 시그니처를 선언해주면 해결할 수 있다.
interface buttonStyleInterface {
[key: string]: string;
}
그런데 여기서 key값에 type을 주고 싶어서 아래와 같이 작성하면 type에러가 발생한다,.
interface buttonStyleInterface {
[key: ButtonTypes]: string;
// An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead
}
인덱스 시그니처의 타입으로는 union type을 사용할 수 없다.
Mapped object type을 사용해야한다.
✅ 해결
type ButtonTypes = 'primary' | 'gray' |'darkGray';
type buttonStyleType = {
[key in ButtonTypes]: string;
}