首页 > 其他分享 >[Typescript] Map a Discriminated Union to an Object

[Typescript] Map a Discriminated Union to an Object

时间:2022-12-13 15:35:03浏览次数:48  
标签:Map search Typescript Union route discriminated type Route

We have a type Route that is a discriminated union of the possible routes in the application. Each route has the properties search and route

type Route =
  | {
      route: "/";
      search: {
        page: string;
        perPage: string;
      };
    }
  | { route: "/about"; search: {} }
  | { route: "/admin"; search: {} }
  | { route: "/admin/users"; search: {} };

 

Expected:

type tests = [
  Expect<
    Equal<
      RoutesObject,
      {
        "/": {
          page: string;
          perPage: string;
        };
        "/about": {};
        "/admin": {};
        "/admin/users": {};
      }
    >
  >
];

 

Way to solve the problem is by Extract the actual route type based on discriminated type:

type RoutesObject = {
  [Key in Route["route"]]: Extract<Route, { route: Key }>["search"];
};

 

A second apparoach:

type RoutesObject = {
  [R in Route as R["route"]]: R["search"];
};

 

标签:Map,search,Typescript,Union,route,discriminated,type,Route
From: https://www.cnblogs.com/Answer1215/p/16978954.html

相关文章

  • WTL CBitmapHyperLink class
    WTLCBitmapHyperLinkclassDownloaddemoproject-32.4KbIntroductionWTLhasa CHyperLink classthatisusedtocreatehyperlinks.Mainfeatu......
  • Unity Hex Map技术测试
    HexMap常用于战棋的地形,最近有这方面的需求,做一个简单的测试,从画一个正六边形开始。0x00.正六边形如上图所示,两个圆,可以很规范的画一个六变形。外圆半径定为:​​publicco......
  • 017.开发请假申请Mapper层
    1.创建请假单实体(com.imooc.oa.entity)LeaveForm.javapackagecom.imooc.oa.entity;importjava.util.Date;publicclassLeaveForm{privateLongformId;......
  • 用通俗易懂的大白话讲解Map/Reduce原理
    下面是我自己的微信公众号(不定期更新JAVA、大数据、个人成长等干货)1、公众号上有经典的技术电子书可以免费领2、大家有问题可以在公众号问我,只要你问了我就会回复(相互交流......
  • python map不一样应用
    mapmap(function,iterable,...)function:针对每个迭代对象的函数iterable可迭代对象注意:function中参数和iterable个数对应单个可迭代对象(不常用)list(map(lam......
  • nmap快速扫描
    快速有效探测端口:nmap-p8080-n--open--min-hostgroup1024--min-parallelism10--host-timeout30-T4-Pn-iLip_list.txt快速探测主机存活nmap-sn192.......
  • nmap快速探测
    1.快速扫描端口nmap  -p8080-n--open--min-hostgroup1024--min-parallelism10--host-timeout30-T4-Pn -iLip_list.txt2.快速探测主机存活nmap-sn19......
  • Npoi.Mapper 日期转换
    问题:Excel文档里有一些列是日期类型的数据,使用Mapper默认的转换,发现生成的实体,在有的系统环境下能正常转换,但是在有的系统环境下,转换的日期出现中文。猜想是Excel文档里,日......
  • 面试之集合整理——重点 Map & List
    一,集合框架图二,遍历方式,及常用方法。map:packagecom.HashMap_Demo;importjava.util.Collections;importjava.util.HashMap;importjava.util.Iterator;importjava.util.......
  • TreeMap使用案例-多个映射(中级版)
    细节问题请看简单版publicclassWordMapn{publicstaticMap<String,List<String>>computeAdjacentWords(List<String>theWords){Map<String,L......