문제점
팀 프로젝트 중...
매너점수 평가 결과를 reduce 함수를 이용하여 객체로 만드는 과정에서 타입 에러가 발생했다.
오류 메세지
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.
No index signature with a parameter of type 'number' was found on type '{}'.

acc의 초기값을 빈 객체{} 로 설정했기 때문에 타입 추론이 제대로 되지 않은 것이 원인이었다.
❌ 해결방안 1 : 인덱스 시그니처 사용 → 해결되지 않음
interface ValuationsObject {
[key: number]: number;
}
const valuationsObject: ValuationsObject = valuations.reduce((acc, { userId, count }) => {
acc[userId] = count;
return acc;
}, {});
❌ 해결방안 2 : as any로 type assertion → 해결은 되었으나 any 때문에 또다른 타입 에러 발생
const valuationsObject = valuations.reduce((acc, { userId, count }) => { acc[userId] = count; return acc; }, {} as any);
이렇게 하니 기존의 타입 에러는 해결이 되었지만, any 때문에 또다른 타입 에러가 발생했다.
그리고 as any를 사용하는 것은 타입스크립트를 사용할 때의 장점을 백 퍼센트 사용하기 어렵게 되므로 이런 식의 해결은 좋지 않다고 생각.
⭕️ 해결방안 3 : acc에 type assertion
const valuationsObject = valuations.reduce((acc, { userId, count }) => { acc[userId] = count; return acc; }, <{ [key: number]: number }>{});
acc 객체가 <{ [key: number]: number }>{} 타입이라고 타입 스크립트에게 알려주어서
타입 스크립트 컴파일러가 type assertion을 제대로 수행할 수 있도록 하여 해결!
'Recap > 에러 해결 기록' 카테고리의 다른 글
| 빌드 중 top level await 에러 (0) | 2024.05.15 |
|---|---|
| 리액트 쿼리 useMutation의 mutationFn은 하나의 argument만 받는다. (0) | 2024.04.26 |
| vercel로 배포 후 새로고침 시 404 이슈와 클라이언트 사이드 라우팅 (1) | 2024.03.01 |
| vercel로 배포 후 proxy 설정하여 CORS 에러 해결하기 (1) | 2024.03.01 |
| Could not resolve dependency:npm ERR! peer next@"^12 || ^13" from next-contentlayer@0.3.4 (0) | 2024.02.16 |