zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

typescript of gt lt union extract
2023-09-14 08:59:11 时间

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 }>>];