【问题标题】:How to get enum size as a type in Typescript如何在 Typescript 中获取枚举大小作为类型
【发布时间】:2021-07-09 13:41:33
【问题描述】:

在 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

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    这是可行的:

    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']
    

    您可以在我的blogthis gist 中找到更多信息

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2015-12-22
      • 2017-01-14
      • 1970-01-01
      • 2022-09-23
      • 2018-10-18
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多