我有一个基于2-3个类型的减速器类型。Store、ReturnStore和Context,默认情况下为void。
如何在Action类型中重用CountReducer类型作为类型参数?
现在,Action需要与CountReducer相同的2-3个类型,这会产生重复的代码,并使应用程序接口变得混乱。
当前代码:
type CountingStore = {
state: "counting";
ctx: number;
};
type Store = StartedStore | CountingStore | EndedStore;
type CountReducer = (s: Store, toAdd: number) => CountingStore;
const CountReducer: CountReducer = (s, toAdd) => ({
state: "counting",
ctx: s.ctx + toAdd
});type Action<Store, ReturnStore, Context = void> = {
act: (() => void) | ((ctx: Context) => void);
stream: Observable<Context>;
reducer: Reducer<Store, ReturnStore, Context>;
};type Actions = {
count: Action<Store, CountingStore, number>;
end: Action<Store, EndedStore>;
restart: Action<Store, StartedStore>;
};未来可能的API设计:
type Action<MyReducer extends Reducer> = "???";您可以在以下位置找到可运行项目中的相关源代码:https://github.com/marcusnielsen/rx-machine/blob/master/src/index.test.ts
发布于 2019-07-17 21:05:46
您可以使用条件类型从reducer函数中提取类型参数:
type ActionFromReducer<T extends (s: any, ctx?: any) => any> =
T extends (s: infer TStore, ctx: infer TContext) => infer TReturnStore ? Action<TStore, TReturnStore, TContext> :
T extends (s: infer TStore) => infer TReturnStore ? Action<TStore, TReturnStore, > :
never;
type Actions = {
count: ActionFromReducer<CountReducer>;
end: ActionFromReducer<EndReducer>;
restart: ActionFromReducer<RestartReducer>;
};https://stackoverflow.com/questions/57076303
复制相似问题