gpt4 book ai didi

Typescript Pick Array 未按预期工作

转载 作者:行者123 更新时间:2023-12-05 05:05:47 30 4
gpt4 key购买 nike

如果我将这一行用作数组,我不确定为什么会出现问题以及如何修复它:

Pick<Author, PickedAuthorFields>[]

Sandbox .

如果我使用 never 而不是条件类型,那么必填作者字段就会出现另一个问题。

Sanbox 2

沙盒 3 可选 ?作者还有另一个问题......

Sanbox 3

许多页面需要此 ApiResBook 通用类型,这些页面将根据请求向具有不同预期输出字段的 api 发出请求。

也许有替代方法,如果需要我可以改变对象的形状。

// 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
}

// 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
}
}

// tests
type BookWithAuthor = ApiResBook<'id', 'name' | 'id'>

// should be ok
const bookWithAuthor1: BookWithAuthor = { book: { id: '1', author: [{ id: '1' }] } }
const bookWithAuthor2: BookWithAuthor = { book: { id: '1', author: [{ name: 'Max' }] } }
const bookWithAuthor3: BookWithAuthor = { book: { id: '1', author: [{ name: 'Max', id: '1' }] } } // why error?

最佳答案

弄清楚了一段时间,但我认为这是解决方案:

type Book = {
id: string
title: string
visible: boolean
author: string
}

type Author = {
id: string
name: string
}

// 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 | null = null,
AuthorObj = {author: Pick<Author, Exclude<PickedAuthorFields, null>>[]}
> = {
book: Pick<Book, PickedBookFields> & (PickedAuthorFields extends null ? {} : AuthorObj)
}


// tests
type BookWithAuthor = ApiResBook<'id', 'name' | 'id'>
type BookWithoutAuthor = ApiResBook<'id'>

// should be ok
const bookWithAuthor0: BookWithoutAuthor = { book: { id: '1' } }
const bookWithAuthor3: BookWithAuthor = { book: { id: '1', author: [{ id: '1', name: 'Max' }] } }

附言。 null 可以替换为 undefined 或任何其他单位类型

关于Typescript Pick Array 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60318679/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com