[Typescript] Map a Discriminated Union to an Object
Maptypescript to object an union
2023-09-14 08:59:11 时间
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"];
};
相关文章
- Go map使用
- UVA 11991 Easy Problem from Rujia Liu?(vector map)
- [TypeScript] Typescript Intersection & Union Types
- [Typescript] Simplify iteration of custom data structures in TypeScript with iterators (backwards iteration with for ... of.. loop)
- [Typescript] Specify Exact Values with TypeScript’s Literal Types
- [Ramda] Declaratively Map Data Transformations to Object Properties Using Ramda evolve
- [TypeScript] Function Overloads in Typescript
- [Typescript] Defining exclusive properties with TypeScript
- [Typescript] Map an Object to a Union of Tuples
- [Typescript] Making TypeScript Stick - 3
- [React Typescript 2022] Use TypeScript to Type a React Class Component
- [React Typescript 2022] Refactor a React Component using TypeScript
- [Typescript] Narrow the unknown Type with TypeScript's Assertion Functions
- [Typescript] Use the Optional Chaining Operator in TypeScript
- [Typescript] Make TypeScript Class Usage Safer with Strict Property Initialization
- [RxJS] Use RxJS mergeMap to map and merge high order observables
- [TypeScript] Function Overloads in Typescript
- golang单元测试类示例代码:reflect.DeepEqual比较两个map的值是否相同
- 【学亮IT手记】SpringMVC增删改查+map数据返回Controller层代码示例
- Power BI for Office 365(六)Power Map简介
- Chrome source code map - fail - cannot debug
- rxjs里的Observable对象和map配合的一个用法
- Qt 多线程之QtConcurrent::map(处理序列容器)
- es6 语法 (map、set和obj 的对比)
- frida构造map和list
- 一脸懵逼学习MapReduce的原理和编程(Map局部处理,Reduce汇总)和MapReduce几种运行方式
- 防火墙——多通道协议与Server-map表项