How to ensure that a partial have a given field with TypeScript?

324 Views Asked by At

I have a type "Post" as follow:

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

I need to use it in a React Native flatlist, where the id is needed. In this case the id is fetched.

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

There keyExtractor is underlined with:

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

I tried to change keyExtractor={(item: Partial) => item.id} to:

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

There data is underlined with:

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

Is there an elegant solution for this?

Thanks

1

There are 1 best solutions below

0
On

I came to use an exclamation mark:

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