【问题标题】:How to ensure that a partial have a given field with TypeScript?如何使用 TypeScript 确保部分具有给定字段?
【发布时间】:2020-12-18 09:46:23
【问题描述】:

我有一个“帖子”类型如下:

interface Post {
  id?: string
  title: string
  content: string
  tags?: string[]
}

我需要在需要 id 的 React Native flatlist 中使用它。在这种情况下,会获取 id。

<FlatList
  data={posts as Array<Partial<Post>>}
  renderItem={({ item }: { item: Partial<Post> }) => <ContentListItem post={item} />}
  keyExtractor={(item: Partial<Post>) => item.id}
  ListHeaderComponent={ListHeaderComponent}
/>

keyExtractor下划线:

Type '(item: Partial<Post>) => string | undefined' is not assignable to type '(item: Partial<Post>, index: number) => string'.

我尝试将 keyExtractor={(item: Partial) => item.id} 更改为:

keyExtractor={(item: {id: string} & Partial<Post>) => item.id}

数据下划线:

Type 'Partial<Post>[]' is not assignable to type 'readonly ({ id: string; } & Partial<Post>)[]'.

有没有一个优雅的解决方案?

谢谢

【问题讨论】:

    标签: typescript react-native typescript-typings react-native-flatlist typescript-partial


    【解决方案1】:

    我来用感叹号了:

    keyExtractor={(item: Partial<Post>) => item.id!}
    

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2019-12-03
      • 2011-07-12
      • 2021-04-23
      相关资源
      最近更新 更多