How can I modify the generic ApiResBook type to handle optional props with input check using the extends keyword?
I have these main types defined, which correspond to fields in a database:
// Main types as in database - should't be changed
type Book = {
id: string
title: string
visible: boolean
author: string
}
type Author = {
id: string
name: string
}
For the API fetch response, I need a generic type that shapes an object based on requested fields
// Inhereted from types from main
type BookFields = keyof Book
type AuthorFields = keyof Author
// type for generating expected fetch response from API
type ApiResBook<
PickedBookFields extends BookFields,
PickedAuthorFields extends AuthorFields | undefined = undefined,
> = {
book: Pick<Book, PickedBookFields> & {
author?: PickedAuthorFields extends AuthorFields ? Pick<Author, PickedAuthorFields> : undefined
}
}
// example of fetching data from the API
async function fn() {
const fetchAPI = <ExpectedData = any>(
apiAction: string,
body: any
): Promise<{ data: ExpectedData } | { error: true }> => {
return new Promise((resolve) => {
fetch(`api`, body)
.then((raw) => raw.json())
.then((parsed: { data: ExpectedData } | { error: true }) => resolve(parsed))
.catch((err) => {
console.log(err)
})
})
}
// response type is { error: true } | {data: { book: { id: string } } }
const response = await fetchAPI<ApiResBook<'id'>>('smth', {})
}
The issue lies with the generic ApiResBook type, as I am unsure how to make certain generic types optional. Test examples are provided:
//tests
type BookOnly = ApiResBook<'id'>
type BookWithAuthor = ApiResBook<'id', 'name'>
// should be ok
const bookOnly: BookOnly = { book: { id: '1' } }
const bookWithAuthor: BookWithAuthor = { book: { id: '1', author: { name: 'Max' } } }
// should result in error
type BookOnly2 = ApiResBook<'propFoesntExist'>
const bookOnlyError: BookOnly = { book: { id: '1', author: {name: 'Max'} } }
const bookWithoutAuthorError: BookWithAuthor = {book: {id: '1'}}