-
[TypeScript] Type 'string[] | undefined' must have a '[Symbol.iterator]()' method that returns an iterator.Trouble Shooting 2023. 4. 24. 23:14
1. 에러 발생
Query string을 핸들링하기 위해 spread 연산자를 활용하여 함수를 작성하던 중 아래와 같은 에러가 발생했습니다.
에러 내용
Type 'string[] | undefined' must have a '[Symbol.iterator]()' method that returns an iterator.// 에러 발생 코드 const handleFilterSelected = (type: string, id: string) => { const anotherType = type === 'note' ? 'brand' : 'note'; const prevFilterList = searchParams.get(type)?.split('|'); const newFilterList = prevFilterList.includes(id) ? prevFilterList.filter((itemId) => itemId !== id) : [...prevFilterList, id]; // 에러 발생 setSearchParams({ [type]: newFilterList, [anotherType]: searchParams.get(anotherType)?.split('|'), }); };
2. 에러 해결
const handleFilterSelected = (type: string, id: string) => { const anotherType = type === 'note' ? 'brand' : 'note'; const prevFilterList = searchParams.get(type)?.split('|') || []; // prevFilterList가 undefined일 때 빈 배열을 기본 값으로 선언 const newFilterList = prevFilterList.includes(id) ? prevFilterList.filter((itemId) => itemId !== id) : [...prevFilterList, id]; setSearchParams({ [type]: newFilterList, [anotherType]: searchParams.get(anotherType)?.split('|') || [], }); };
3. 고찰
MDN 문서에서는 Array 인스턴스의 [@@iterator]() 메서드를 iterable protocol을 구현하고 spread 구문과 for...of 반복문과 같은 반복이 예상되는 대부분의 구문에서 배열을 사용할 수 있게 허용한다고 설명하고 있습니다.
The [@@iterator]() method of Array instances implements the iterable protocol and allows arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the array.
그런데 위의 에러 발생 코드에서는 query string의 유무에 따라 undefined가 될 수 있는 prevFilterList 변수에 spread 연산자를 적용하려 했기 때문에 에러가 발생하게 되었고, 해당 변수가 undefined일 때에는 빈 배열을 기본 값으로 할당하여 에러를 해결했습니다.
참고 자료
- [MDN] Array.prototype[@@iterator]()
- Type '~[] | undefined' must have a '[Symbol.iterator]()' method that returns an iterator 에러 해결
'Trouble Shooting' 카테고리의 다른 글