假设我们userReducer定义如下:
function userReducer(state: string, action: UserAction): string {
switch (action.type) {
case "LOGIN":
return action.username;
case "LOGOUT":
return "";
default:
throw new Error("Unknown 'user' action");
}
}
Run Code Online (Sandbox Code Playgroud)
定义UserAction类型的最佳方法是什么,以便可以dispatch使用username有效载荷和不使用有效载荷进行调用:
dispatch({ type: "LOGIN", username: "Joe"}});
/* ... */
dispatch({ type: "LOGOUT" });
Run Code Online (Sandbox Code Playgroud)
如果 type 是这样定义的:
type UserActionWithPayload = {
type: string;
username: string;
};
type UserActionWithoutPayload = {
type: string;
};
export type UserAction = UserActionWithPayload | UserActionWithoutPayload;
Run Code Online (Sandbox Code Playgroud)
在“登录”情况下,编译器在减速器中抛出和错误: TS2339: Property 'username' does not …