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



在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"
}

需要明确的是,我有兴趣将其作为一个类型NOT值。我知道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']

你可以在我的博客和这个要点中找到更多信息

最新更新