[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 Extract
type 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 }>>];