首页 > 解决方案 > React Native SectionList:什么是正确的 TypeScript 类型

问题描述

我正在使用 TypeScript 构建一个 React Native 应用程序。我正在尝试使用SectionList. 我遵循了文档,这是我的代码:

  renderSectionHeader = ({ section: { title } }: { section: { title: string } }) => (
    <ListItem title={title} />
  );

  render() {
    const { sections } = this.props;
    return (
      <SafeAreaView style={styles.container}>
        <SectionList
          keyExtractor={this.keyExtractor}
          sections={[
            {title: 'Title1', data: ['item1', 'item2']},
            {title: 'Title2', data: ['item3', 'item4']},
            {title: 'Title3', data: ['item5', 'item6']},
          ]}
          renderItem={this.renderItem}
          renderSectionHeader={this.renderSectionHeader}
        />
      </SafeAreaView>
    );
  }

但是该行renderSectionHeader={this.renderSectionHeader}会引发以下 TSLint 错误:

[ts]
Type '({ section: { title } }: { section: { title: string; }; }) => Element' is not assignable to type '(info: { section: SectionListData<any>; }) => ReactElement<any> | null'.
  Types of parameters '__0' and 'info' are incompatible.
    Type '{ section: SectionListData<any>; }' is not assignable to type '{ section: { title: string; }; }'.
      Types of property 'section' are incompatible.
        Type 'SectionListData<any>' is not assignable to type '{ title: string; }'.
          Property 'title' is missing in type 'SectionListData<any>'. [2322]

SectionList破碎的种类吗?还是例子错了?还是我做错了什么?

标签: typescriptreact-nativetypescript-typingstypescript-typesreact-native-sectionlist

解决方案


interface Data {
...
}

const MySectionList = SectionList as SectionList<Data>;

<MySectionList
...
/>

为我工作


推荐阅读