gpt4 book ai didi

typescript - 如何在 Typescript 中获取枚举大小作为类型

转载 作者:行者123 更新时间:2023-12-04 14:54:35 26 4
gpt4 key购买 nike

在 Typescript 中,有一种方法可以获取数组或元组的大小并将其用作类型:

type Tuple = [number, string, boolean];
type Arr = [0, 1, 2];

type LengthOf<T extends any[]> = T["length"];

type Test = LengthOf<Tuple>; // 3
type Test2 = LengthOf<Arr>; // 3

有没有办法用枚举做同样的事情(提取长度/大小)?枚举示例:

enum Example {
how = "how",
to = "to",
count = "count",
enum = "enum",
entries = "entries"
}

需要说明的是,我有兴趣将其作为一种不是值的类型。我知道 Object.keys(Example).length

最佳答案

这是可行的:

enum Example {
how = "how",
to = "to",
count = "count",
enum = "enum",
entries = "entries"
}
// credits goes to https://stackoverflow.com/a/50375286
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I
) => void
? I
: never;

// credits goes to https://github.com/microsoft/TypeScript/issues/13298#issuecomment-468114901
type UnionToOvlds<U> = UnionToIntersection<
U extends any ? (f: U) => void : never
>;

type PopUnion<U> = UnionToOvlds<U> extends (a: infer A) => void ? A : never;

type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;

type UnionToArray<T, A extends unknown[] = []> = IsUnion<T> extends true
? UnionToArray<Exclude<T, PopUnion<T>>, [PopUnion<T>, ...A]>
: [T, ...A];


type Result = UnionToArray<keyof typeof Example>['length']

您可以在我的 blog 中找到更多信息在this要点

关于typescript - 如何在 Typescript 中获取枚举大小作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68317823/

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