gpt4 book ai didi

TypeScript - 从具有特定类型的所有属性中获取类型

转载 作者:行者123 更新时间:2023-12-02 17:57:52 27 4
gpt4 key购买 nike

我有一个来自 OpenAPI 规范的过滤器对象;像这样:

export interface Filters {
field1: string[]
field2: string[]
field3: boolean
field4: number
}

我想通过选择属性的类型从该过滤器接口(interface)派生类型:

类似于:

export type MultivalueFields = Select<Filters, string[]>
// type MultivalueFields = 'field1' | 'field2'

有内置的功能吗?怎样才能得到想要的结果?

最佳答案

您可以构建如下实用程序类型:

type Values<T> = T[keyof T]
type Select<T, SelectType> = Values<{
[Prop in keyof T]: T[Prop] extends SelectType ? Prop : never
}>

// typeof A = 'field1'
type A = Select<{field1: string[], field2: string}, string[]>

所有功劳归于来自乌克兰的@captain-yossarian

关于TypeScript - 从具有特定类型的所有属性中获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75221146/

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