[Typescript] Extract the Discriminator from a Discriminated Union

For example we have a discriminated union type:

export type Event =
  | {
      type: "click";
      event: MouseEvent;
    }
  | {
      type: "focus";
      event: FocusEvent;
    }
  | {
      type: "keydown";
      event: KeyboardEvent;
    };

 

We only wnat to get Discriminator from it, which is 

"click" | "focus" | "keydown"
 
export type Event =
  | {
      type: "click";
      event: MouseEvent;
    }
  | {
      type: "focus";
      event: FocusEvent;
    }
  | {
      type: "keydown";
      event: KeyboardEvent;
    };

type EventType = Event["type"];

type tests = [Expect<Equal<EventType, "click" | "focus" | "keydown">>];

 

posted @ 2022-12-11 20:18  Zhentiw  阅读(47)  评论(0编辑  收藏  举报