首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从reducer函数推断类型

从reducer函数推断类型
EN

Stack Overflow用户
提问于 2019-07-17 20:51:46
回答 1查看 56关注 0票数 1

我有一个基于2-3个类型的减速器类型。StoreReturnStoreContext,默认情况下为void

如何在Action类型中重用CountReducer类型作为类型参数?

现在,Action需要与CountReducer相同的2-3个类型,这会产生重复的代码,并使应用程序接口变得混乱。

当前代码:

代码语言:javascript
复制
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
});
代码语言:javascript
复制
type Action<Store, ReturnStore, Context = void> = {
  act: (() => void) | ((ctx: Context) => void);
  stream: Observable<Context>;
  reducer: Reducer<Store, ReturnStore, Context>;
};
代码语言:javascript
复制
type Actions = {
  count: Action<Store, CountingStore, number>;
  end: Action<Store, EndedStore>;
  restart: Action<Store, StartedStore>;
};

未来可能的API设计:

代码语言:javascript
复制
type Action<MyReducer extends Reducer> = "???";

您可以在以下位置找到可运行项目中的相关源代码:https://github.com/marcusnielsen/rx-machine/blob/master/src/index.test.ts

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-17 21:05:46

您可以使用条件类型从reducer函数中提取类型参数:

代码语言:javascript
复制
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>;
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57076303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档