Reputation: 37066
I want to make api request like this:
// api Request
const body: ReqBody = { book: ['id', 'title'], author: ['name']}
const fn = async () => {
const book: BookPropsOk = await fetch('api', {body: JSON.stringify(body)}) as any
}
Problem is idn how to make type with optional author if i will fetch only book fields?
// types
export type Book = {
id: string
title: string
}
export type Author = {
id: string
name: string
}
type BookFields = 'id' | 'title'
type AuthorFields = 'id' | 'name'
// generic response type from api (CHANGE THIS)
type ApiResBook<PickedBookFields extends BookFields, PickedAuthorFields extends AuthorFields> =
Pick<Book, PickedBookFields> & {
author: Pick<Author, PickedAuthorFields>
}
type BookPropsOk = ApiResBook<'id' | 'title', 'name'>
type ReqBody = {
book: BookFields[]
author?: AuthorFields[]
}
// what if i want to fetch only book without author?
type BookPropsHowToMakeAuthorOptional = ApiResBook<'id' | 'title'>
Upvotes: 1
Views: 63
Reputation: 37066
Hm, seems extends and pick works with never default:
type ApiResBook<PickedBookFields extends BookFields, PickedAuthorFields extends AuthorFields = never> =
Pick<Book, PickedBookFields> & {
author: Pick<Author, PickedAuthorFields>
}
Upvotes: 1