[英]Generic typescript with optional extends
如何使用擴展進行輸入檢查使通用 ApiResBook 類型與可選道具一起使用?
沙盒。
我有這個主要類型,與數據庫字段相同:
// 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
}
對於 api fetch 響應,我需要通用類型,該類型將根據請求的字段塑造對象
// 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
}
}
// fetch example of usage
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', {})
}
問題在於通用 ApiResBook 類型,我不知道如何將一些通用類型設為可選。 測試示例包括:
//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 be error
type BookOnly2 = ApiResBook<'propFoesntExist'>
const bookOnlyError: BookOnly = { book: { id: '1', author: {name: 'Max'} } }
const bookWithoutAuthorError: BookWithAuthor = {book: {id: '1'}}
自己解決了這個問題:/似乎工作正常。
type ApiResBook<
PickedBookFields extends BookFields,
PickedAuthorFields extends AuthorFields | undefined = undefined,
> = {
book: Pick<Book, PickedBookFields> & {
author: PickedAuthorFields extends AuthorFields ? Pick<Author, PickedAuthorFields> : undefined
}
}
沙盒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.