i9o*_*9or 4 types typescript reactjs react-hooks
假设我们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 exist on type 'UserAction'. Property 'username' does not exist on type 'UserActionWithoutPayload'.
如果类型是用可选成员定义的:
export type UserAction = {
type: string;
username?: string;
}
Run Code Online (Sandbox Code Playgroud)
然后编译器显示此错误: TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
这里缺少什么?也许整个方法是错误的?
项目使用 TypeScript 3.8.3 和 React.js 16.13.0。
经过数小时的挖掘和试验,通过 Typescriptenum和联合类型为操作找到了一个非常优雅的解决方案:
enum UserActionType {
LOGIN = "LOGIN",
LOGOUT = "LOGOUT"
}
type UserState = string;
type UserAction =
| { type: UserActionType.LOGIN; username: string }
| { type: UserActionType.LOGOUT }
function userReducer(state: UserState, action: UserAction): string {
switch (action.type) {
case UserActionType.LOGIN:
return action.username;
case UserActionType.LOGOUT:
return "";
default:
throw new Error();
}
}
function App() {
const [user, userDispatch] = useReducer(userReducer, "");
function handleLogin() {
userDispatch({ type: UserActionType.LOGIN, username: "Joe" });
}
function handleLogout() {
userDispatch({ type: UserActionType.LOGOUT });
}
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
使用上述方法没有错误或警告,另外还有一个非常严格的操作使用合同。