Home > Net >  React Native Flatlist with Typescript:Property 'data' is optional in type but required in
React Native Flatlist with Typescript:Property 'data' is optional in type but required in

Time:05-05

Here's my FlatList:

  <FlatList
    {...omit(this.props, [
      "id",
      "loading",
    ])}
    nestedScrollEnabled
    renderItem={this.renderItem}
    onEndReached={this.onEndReached}
    ListFooterComponent={this.renderFooter}
  />

Here's a renderItem:

  @autobind
  renderItem<
    I extends ILVITem,
    IX extends { toString: () => string }
  >({ item, index }: { item: I; index: IX }) {
    if (!isFunction(this.props.itemConfig)) {
      return null;
    }
    const itemConfig = this.props.itemConfig(item);
    if (isEmpty(itemConfig)) {
      return null;
    }
    return (
      <ListRow
        throwData={item}
        title={this.titleState(item, itemConfig)}
        subtitle={this.subtitleState(item, itemConfig)}
      />
    );
  }

My problem:

 Property 'data' is optional in type '{ nestedScrollEnabled: true; renderItem: <I extends ILVITem, IX extends { toString: () => string; }>({ item, index }: { item: I; index: IX; }) => Element | null; onEndReached: () => void; ListFooterComponent: () => Element | null; ... 15 more ...; onPress?: (() => any) | undefined; }' but required in type 'Readonly<FlatListProps<string>>'.

I don't see any reason of this error. Is there any way to make data not optional?

in ILVITem interface data is not optional.

CodePudding user response:

Had almost the same issue. If you have data in this.props and use something like spread operator, pick, omit in FlatList props - TS won't "understand" that. You need to pass data prop in any case:

  <FlatList
    {...omit(this.props, [
      "id",
      "loading",
    ])}
    data={this.props.data}
    nestedScrollEnabled
    renderItem={this.renderItem}
    onEndReached={this.onEndReached}
    ListFooterComponent={this.renderFooter}
  />
  • Related