프론트엔드 개발/Typescript
타입스크립트 에러) Type 'undefined' cannot be used as an index type.
Ella Seon
2023. 3. 16. 11:42
✅에러원인
- 공통 버튼 컴포넌트를 만들고 있었다. theme.tsx 에서 colors를 props 로 받아오는 걸로 설정했는데 아래와 같이 에러가 생겼다.
에러메세지 : Type 'undefined' cannot be used as an index type.
index 타입에는 undefined가 들어갈수 없다는 것이었다.
interface ButtonProps에서 color 부분이 ? 옵션으로 설정되어있어서 string | undefined 로 인식될 것이다.
✅에러 해결
- 따라서, undefined 값을 처리해주는 Narrowing 기법을 삼항연산자로 표시했다.
const colorStyles = css<ButtonProps>`
/* 색상 */
${({ theme, color }) => {
const selected =
typeof color !== "undefined" // undefined 가 아니라면
? theme.colors[color] // 내가 기입한 color 로 받고
: theme.colors["green"]; // undefined 라면 기본 색상인 green으로 해주어라
return css`
background: ${selected};
&:active {
background: #ffffff;
}
&:disabled {
background: #c4c4c4;
}
`;
}}
`;