[Typescript] Extracting Members of a Discriminated union - Extract<T, U>

Give a discriminated union:

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

 

I want to get only Click event, we can reply on Extracttype utilites.

type ClickEvent = Extract<Event, { type: "click" }>;

 

import { Equal, Expect } from "../helpers/type-utils";

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

type ClickEvent = Extract<Event, { type: "click" }>;

type tests = [Expect<Equal<ClickEvent, { type: "click"; event: MouseEvent }>>];

 

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