TypeScript:从可区分的联合派生地图

TypeScript: derive map from discriminated union

我有一个可区分的联合类型,它根据字符串文字字段区分类型。我想派生一个映射类型,将联合中的所有类型映射到它们相应的鉴别器文字值。

例如

export type Fetch = {
    type: 'fetch',
    dataType: string
};

export type Fetched<T> = {
    type: 'fetched',
    value: T
};

// union type discriminated on 'type' property
export type Action =
    | Fetch
    | Fetched<Product>;

// This produces a type 'fetch' | 'fetched'
// from the type 
type Actions = Action['type'];

// I want to produce a map type of the discriminator values to the types 
// comprising the union type but in an automated fashion similar to how I
// derived my Actions type.
// e.g.
type WhatIWant = {
    fetch: Fetch,
    fetched: Fetched<Product>
}

这在 TypeScript 中可行吗?

随着 TypeScript 2.8 中 conditional types 的引入,您可以定义一个类型函数,给定一个可区分的联合以及判别式的键和值,生成联合的单个相关成分:

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

As of TypeScript 2.8, you can also use the built-in Extract utility type to simplify the above conditional:

type DiscriminateUnion<T, K extends keyof T, V extends T[K]> 
 = Extract<T, Record<K, V>>

如果你想用它来构建地图,你也可以这样做:

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

所以在你的情况下,

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

如果你检查它,它是:

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

如愿,我想。希望有所帮助;祝你好运!