[TypeScript] 객체 프로퍼티에 string으로 접근할 경우 에러

HYEJIN·2023년 1월 30일
0

에러일지

목록 보기
2/2

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

  • 위 오류를 만나게 되었는데, 자바스크립트에서 일반적으로 객체에 프로퍼티로 string을 넘기는 것이 문제가 되지 않는데 타입스크립트에서는 이 부분이 문제가 된다.
interface ButtonProps {
  width?: string;
  height?: string;
  varient?: 'default' | 'danger' | 'normal';
}
const colors = {
  default: 'rgb(36, 41, 47)',
  danger: 'rgb(207, 34, 46)',
  normal: 'rgb(9, 105, 218)',
};

export const NoneStyleButton = styled.button<ButtonProps>`
  width: ${(props) => props.width};
  height: ${(props) => props.height};
  color: ${(props) =>
    props.varient ? colors[props?.varient] : colors['default']};

`;

props.varient ? colors[props?.varient] : colors['default']};
해당 부분에서 오류가 났다.
이유는 varient가 string인데 string으로는 colors 객체에 접근을 할 수 없기 때문에다.


해결방법

1번째 방법 : string literal 타입의 key로 접근한다.
2번째 방법 : 객체의 타입을 선언할 때 index signature을 사용하면 string으로 접근할 수 있다.

index signature

type Varient = 'default' | 'danger' | 'normal';
interface ButtonProps {
  width?: string;
  height?: string;
  varient?: Varient;
}
type colorType = {
  [key in Varient]: string; // index signature
};
const colors: colorType = {
  default: 'rgb(36, 41, 47)',
  danger: 'rgb(207, 34, 46)',
  normal: 'rgb(9, 105, 218)',
};

colors에 오는 프로퍼티에 좁은 범위로 제한을 주기 위해 Varient에 mapped type을 사용하였고,
colors객체에 타입을 index signiture로 변경하였다.

0개의 댓글