【发布时间】:2018-11-22 12:43:04
【问题描述】:
我遵循Improved Redux type safety with TypeScript 2.8 中显示的模式,但我想添加一个转折点。我的一些操作可以在不同的上下文中重复使用,但需要一些额外的识别信息才能在 reducer 中对它们进行分类。
我想我可以通过添加一些高阶动作创建者修饰符来解决这个问题并保持我的代码简短。这些将接收现有的动作创建者并返回一个新的动作创建者,它将一些信息附加到我的 Flux 标准动作的 meta 键。
// Removed `payload` and `error` for this reproduction
interface FluxStandardAction<T extends string, Meta> {
type: T;
meta?: Meta;
}
// Our basic actions
enum ActionType {
One = "one",
Two = "two",
}
interface Action1 {
type: ActionType.One;
}
interface Action2 {
type: ActionType.Two;
}
type Action = Action1 | Action2;
function action1(): Action1 {
return { type: ActionType.One }
}
function action2(): Action2 {
return { type: ActionType.Two }
}
// Higher order action modifiers that augment the meta
interface MetaAlpha {
meta: {
alpha: string;
}
}
function addMetaAlpha<T extends string, M extends {}, A extends FluxStandardAction<T, M>>(action: () => A, alpha: string) {
return function (): A & MetaAlpha {
let { type, meta } = action();
return { type, meta }; // Error here
}
}
这会产生错误:
Type '{ type: T; meta: M; }' is not assignable to type 'A & MetaAlpha'.
Object literal may only specify known properties, but 'type' does not exist in type 'A & MetaAlpha'. Did you mean to write 'type'?
虽然我很高兴能更好地理解此错误消息,但我的问题实际上是关于哪些技术适合构建高阶动作创建者。
meta 键是实现高阶动作创建器的合适方法吗?如果是这样,我如何以编译器满意的方式实现addMetaAlpha?处理这些增强操作的类型安全化简器会是什么样子?
【问题讨论】:
-
请查看redux-fluent 以获得类型安全的开发人员体验。
标签: typescript redux