ค้นหาเว็บไซต์

วิธีการรับขนาดของ enum เป็นประเภทใน 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? ตัวอย่าง enum:

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

และเพื่อความชัดเจน ฉันสนใจที่จะได้สิ่งนี้เป็นประเภท ไม่ใช่ ค่า ฉันรู้เกี่ยวกับ Object.keys(Example).length

คำตอบ #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']

คุณสามารถหาข้อมูลเพิ่มเติมได้ในบล็อกของฉันและใน gist นี้