小编i9o*_*9or的帖子

如何在 Typescript 中为 React useReducer 钩子操作创建类型定义?

假设我们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 …

types typescript reactjs react-hooks

4
推荐指数
1
解决办法
3518
查看次数

标签 统计

react-hooks ×1

reactjs ×1

types ×1

typescript ×1