FlatList renderItem에 타입 지정하기

이강혁·2024년 1월 4일
0

막힘

목록 보기
7/11

Udemy react native 강의를 들으면서 FlatList를 사용하는 파트가 나와서 코드를 따라 치고 있었다. 이번 프로젝트에서 react native와 타입스크립트, 그리고 nativewind를 사용할 예정이어서 강의와는 조금 다르게 입력하고 있었는데

<StyledFlatList data={courseGoals} alwaysBounceVertical={false} className="flex-1"
  renderItem={(itemData) =>
    <StyledView className="m-2 rounded-md bg-[#5e0acc] p-2">
      <StyledText onPress={deleteHandler} className="text-white">{itemData.item}</StyledText>
    </StyledView>
} />

이 부분에서

'unknown' 형식은 'ReactNode' 형식에 할당할 수 없습니다.

라는 에러가 나왔다.

공식문서를 찾아보니까 renderItem 내부에 있는 컴포넌트를 따로 꺼내고, FlatList 안에 넣던데 그렇게하니까

const Item = (item: string) => (
  <StyledView className="m-2 rounded-md bg-[#5e0acc] p-2">
    <StyledText onPress={deleteHandler} className="text-white">{item}</StyledText>
  </StyledView>
)
<StyledFlatList data={courseGoals} alwaysBounceVertical={false} className="flex-1"
  renderItem={({ item }) =>
    <Item item={item} />
} />

'{ item: unknown; }' 형식은 'string' 형식에 할당할 수 없습니다.

이런 에러가 나왔다. 공식문서를 보니까 data안에 있는 타입을 인식해서 알아서 item의 타입을 추측해주는 것 같던데 왜 안 되는지 모르겠다.
Chat GPT한테 물었는데도 코드 모양만 조금 달라질 뿐 여전히 에러는 해결을 못해줬다.

그래서 일단 공식문서에 있는 코드를 그대로 들고왔다.
공식문서의 코드에는 data의 타입을 잘 인식해서 renderItem에도 가져왔는데 내 코드에는 왜 안 되는지 모르겠다.

블로그 찾아보니까 as string 써서 해결하길래

<StyledFlatList data={courseGoals} alwaysBounceVertical={false} className="flex-1"
    renderItem={(itemData) =>
    <StyledView className="m-2 rounded-md bg-[#5e0acc] p-2">
        <StyledText onPress={deleteHandler} className="text-white">{itemData.item as string}</StyledText>
    </StyledView>
} />

해당 부분에 "as string" 추가해주니까 해결 됐다.

profile
사용자불량

0개의 댓글