为了让我使用Redux类型安全,我提出了以下结构:
export interface Action<T extends string, P> {
readonly type: T;
readonly payload: P;
};
export interface ActionBuilder<T extends string, P> {
readonly type: T;
readonly action: Action<T, P>;
with(payload: P) : Action<T, P>;
};
const actionBuilder: <T extends string>(type: T) => <P>() => ActionBuilder<T, P> =
<T extends string>(type: T) => <P>() => <any>({with: (payload: P) => ({type, payload})});
const foo = actionBuilder("Foo")<{bar: string}>();
const bar = actionBuilder("Bar")<void>();
function test(action: typeof foo.action | typeof bar.action) {
switch(action.type) {
case "Foo": {
const la = action.payload.bar; // compiler correctly infers that "la" is a string
break;
}
case bar.type: {
const la = action.payload; // compiler correctly infers that "la" is a void
}
}
}
test(foo.with({bar: "yeah"}))
我唯一不喜欢的就是拥有这种假动作&#34;我刚刚在&#34; test&#34; -signature中使用ActionBuilder中的字段来获取最终操作类型的钩子。知道如何让这更好吗?