我有一个对象链接:
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 };
我应该如何像Exclud
或Pick
那样转换它?
答案 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