首页 > 其他分享 >[Typescript] Extracting Members of a Discriminated union - Extract<T, U>

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

时间:2022-12-11 20:24:19浏览次数:52  
标签:KeyboardEvent Typescript union Extract focus Discriminated type event

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

 

标签:KeyboardEvent,Typescript,union,Extract,focus,Discriminated,type,event
From: https://www.cnblogs.com/Answer1215/p/16974332.html

相关文章

  • TypeScript 类型声明文件
    类型声明文件:用来为已存在的JS库提供类型信息。TS中的两种文件类型.ts文件(是implementation代码实现文件)既包含类型信息又可执行代码。可以被编译为.j......
  • 在 React 中使用 TypeScript
    如何在React项目中使用TS,包括以下内容:使用CRA创建支持TS的项目TS配置文件tsconfig.jsonReact中的常用类型使用CRA创建支持TS的项目React脚手......
  • 游戏开发33课 typescript 遍历
    一、for..of方法这是最常用的方法,遍历的值是数组中的value值letsomeArray=[1,"string",false];for(letentryofsomeArray){console.log(entry);//1,"strin......
  • 【mySQL】【数据库】union与or的区别--为什么建议用union代替or?
    LeetCode595.大的国家点击直达如果一个国家满足下述两个条件之一,则认为该国是大国:面积至少为300万平方公里(即,3000000km2),或者人口至少为2500万(即25000000)编写......
  • [Typescript] 133. Medium - All
    Returnstrueifallelementsofthelistareequaltothesecondparameterpassedin,falseifthereareanymismatches.ForexampletypeTest1=[1,1,1]ty......
  • [Typescript] 131. Extreme - Query String Parser
    You'rerequiredtoimplementatype-levelparsertoparseURLquerystringintoaobjectliteraltype.Somedetailedrequirements:Valueofakeyinquerystr......
  • TypeScript 开发环境搭建
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......
  • 一. TypeScript基础
    1.TS运行环境方式一:通过webpack,配置本地的TypeScript编译环境和开启一个本地服务,可以直接运行在浏览器上方式二:通过ts-node库,为TypeScript的运行提供执行环境安装ts......
  • [Typescript] 130. Hard - Replace Union
    Givenan unionoftypes and arrayoftypepairs toreplace([[string,number],[Date,null]]),returnanewunionreplacedwiththe typepairs. /*____......
  • typeScript学习
    typeScript配置文件如果一个目录下存在一个tsconfig.json文件,那么它意味着这个目录是TypeScript项目的根目录。tsconfig.json文件中指定了用来编译这个项目的根文件和编......