typescript - 带有可选扩展的通用打字稿
问题描述
如何使用扩展输入检查使通用 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 获取响应,我需要通用类型,它将根据请求的字段塑造对象
// 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
}
}
沙盒。