gpt4 book ai didi

条件类型的 typescript 枚举类型检查?

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

我有接受枚举值作为数字或字符串的 Restful 服务,但始终只返回数字。有没有办法输入它们?

这是我想要的,但它在语法上无效:

enum Features {
"A" = 1,
"B" = 2,
"C" = 2
}

type EnumOrString<T> = T extends enum
? T | keyof T
: T

declare function getData(featureFilter: EnumOrString<Features>[]): Features[]

getData 获取枚举值数组或枚举键,但仅返回枚举值。

I also would want to extend this to mapped types like DeepPartial以便任何嵌套枚举都得到这种处理 - 无需具有由请求和响应划分的单独类型层次结构。

最佳答案

我认为“识别枚举”这件事现在是不可能的。即使可以,您也无法以编程方式将 Features 类型(它是 Features 枚举的一个元素)转换为 typeof Features 类型(从键到 Features 元素的映射)首先不知道Features。同样:例如,类型 Features.B 对字符串文字 "B" 一无所知。只有 typeof Features 具有类似 {B: Features.B} 的属性。如果您希望类型函数从 Features 转换为 Features | keyof typeof Features,你需要明确提及typeof Features。因此,即使您拥有梦想中的 extends enum 表示法,您仍然需要使用您关心的映射列表来编写替换代码。对不起。


仅解决递归部分,如果它很重要,这里是我如何递归处理一个类型以用枚举值和相关键的联合替换一个已知枚举值:

enum Features {
"A" = 1,
"B" = 2,
"C" = 2
}
type ValueOf<T> = T[keyof T]
type FeatureKey<T extends Features> =
Extract<ValueOf<{
[K in keyof typeof Features]: [K, typeof Features[K]]
}>, [any, T]>[0]

type DeepFeaturesOrKey<T> =
T extends Features ? (T | FeatureKey<T>) :
T extends Array<infer L> ? DeepFeaturesOrKeyArray<L> :
T extends object ? { [K in keyof T]: DeepFeaturesOrKey<T[K]> } : T

interface DeepFeaturesOrKeyArray<L> extends Array<DeepFeaturesOrKey<L>> { }

如果您没有指定整个事物(例如,您正在使用 discriminated union 锁定特定枚举值),那么棘手的部分是提取枚举的一个子集,当然,还有整个深层次的东西避免可怕的“循环引用”错误消息的数组技巧 here :

Similar to union and intersection types, conditional types are not permitted to reference themselves recursively (however, indirect references through interface types or object literal types are allowed)

让我们测试一下:

interface Foo {
bar: string,
baz: Features,
qux: {
a: Features[],
b: boolean
},
quux: Features.A,
quuux: Features.B
}

type DeepFeaturesOrKeyFoo = DeepFeaturesOrKey<Foo>
declare const deepFeaturesOrKeyFoo: DeepFeaturesOrKeyFoo
deepFeaturesOrKeyFoo.bar; // string
deepFeaturesOrKeyFoo.baz; // Features | "A" | "B" | "C"
deepFeaturesOrKeyFoo.qux.a[1]; // Features | "A" | "B" | "C"
deepFeaturesOrKeyFoo.qux.b; // boolean
deepFeaturesOrKeyFoo.quux; // Features.A | "A"
deepFeaturesOrKeyFoo.quuux; // Features.B | "B" | "C"
// note that the compiler considers Features.B and Features.C to be the
// same value, so this becomes Features.B | "B" | "C"

看起来不错。希望对您有所帮助。

关于条件类型的 typescript 枚举类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452032/

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