打字稿将化简类型转换为动作

时间:2019-04-11 06:41:45

标签: typescript

我有一个对象链接:

const reducers = {
  increment: (state: State, payload: number) => {
    return { count: state.count + payload };
  },
  decrement: (state: State, payload: number) => {
    return { count: state.count - payload };
  },
  console: (state: State, payload: string) => {
    console.log(payload);
    return { count: state.count };
  },
};

如果我想得到这样的类型:

type reducerType =
  | { type: 'increment'; payload: number }
  | { type: 'decrement'; payload: number }
  | { type: 'console'; payload: string };

我应该如何像ExcludPick那样转换它?

1 个答案:

答案 0 :(得分:2)

首先让我们使用

从常量中提取类型
type Reducer = typeof reducers;

然后获取有效载荷的类型

type ExtractPayload<T> = T extends (arg1: any, payload: infer U) => any ? U : never;

我们需要的另一个工具是减速器的类型

type ToReducerType<K extends KeyT, T> = { "type": K, payload: T };

(暂时忘记KeyT) 现在我们可以定义tho

type ToReducersType<T> = { [P in keyof T]: ToReducerType<P, ExtractPayload<T[P]>> }[keyof T];

应该做你想做的事。

这里是整个示例tsplayground