3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactNative+TypescriptでFlatListを使った時につまずいたポイント

Posted at

FlatListでkeyExtractorに値を割り当てるときに引っかかったのでメモ。

interface Props {
  items: { id: number; title: string }[]
}

<FlatList
 data={items}
 renderItem={({ item }) => <Text>{item.title}</Text>}
 keyExtractor={item => item.id}
/>

このようにkeyExtractorに要素のid(number型)を割り当てたところ以下のメッセージが出た。

[ts]
型 '(item: { id: number; title: string; }) => number' を型 '(item: { id: number; title: string; }, index: number) => string' に割り当てることはできません。
  型 'number' を型 'string' に割り当てることはできません。

keyExtractorにはstring型で一意になる要素を割り当てなければいけないらしい…。

<FlatList
  data={items}
  renderItem={({ item }) => <Text>{item.title}</Text>}
  keyExtractor={item => `${item.id}`}
/>

item.idをstring型に変換して解決。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?