TypeScript: derive map from discriminated union

瘦欲@ 提交于 2019-11-30 15:27:47

With the introduction of conditional types in TypeScript 2.8, you can define a type function which, given a discriminated union and the key and value of the discriminant, produces the single relevant constituent of the union:

type DiscriminateUnion<T, K extends keyof T, V extends T[K]> = 
  T extends Record<K, V> ? T : never

And if you wanted to use that to build up a map, you can do that too:

type MapDiscriminatedUnion<T extends Record<K, string>, K extends keyof T> =
  { [V in T[K]]: DiscriminateUnion<T, K, V> };

So in your case,

type WhatIWant = MapDiscriminatedUnion<Action, 'type'>;

which, if you inspect it, is:

type WhatIWant = {
  fetch: {
    type: "fetch";
    dataType: string;
  };
  fetched: {
    type: "fetched";
    value: Product;
  };
}

as desired, I think. Hope that helps; good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!