You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript定义useReducer的Action类型时,ACTIONS命名空间找不到报错

解决TypeScript中Action类型使用ACTIONS常量报错的问题

你的代码中出现Cannot find namespace 'ACTIONS'错误,原因是ACTIONS是JavaScript值(对象),TypeScript类型系统无法直接在类型定义中引用值。要在Action类型里复用ACTIONS的常量值,需要先从该对象提取对应的类型,再在类型定义中使用。

另外注意你的代码里存在两处拼写错误:

  • ADD_CATEGORIS 应该是 ADD_CATEGORIES
  • UPDATE_CATEGPRIES 应该是 UPDATE_CATEGORIES

修正后的完整代码

import { CategoryType } from "../../types/CategoryItemCount";
import { ModelErrorType } from "../../types/ModelError";

export const ACTIONS = {
  SET_CATEGORIES: "SET_CATEGORIES",
  ADD_CATEGORIES: "ADD_CATEGORIES", // 修正拼写错误
  UPDATE_CATEGORIES: "UPDATE_CATEGORIES", // 修正拼写错误
  DELETE_CATEGORIES: "DELETE_CATEGORIES",
  SET_MODEL_ERRORS: "SET_MODEL_ERRORS",
  SENDING_REQUEST: "SENDING_REQUEST",
  REQUEST_COMPLETED: "REQUEST_COMPLETED",
};

// 从ACTIONS对象提取所有action类型值的联合类型(可选,用于统一约束type字段)
export type ActionType = typeof ACTIONS[keyof typeof ACTIONS];

export type Action =
  | { type: typeof ACTIONS.SET_CATEGORIES; payload: CategoryType[] }
  | { type: typeof ACTIONS.ADD_CATEGORIES; payload: CategoryType }
  | { type: typeof ACTIONS.UPDATE_CATEGORIES; payload: CategoryType }
  | { type: typeof ACTIONS.DELETE_CATEGORIES; payload: number }
  | { type: typeof ACTIONS.SET_MODEL_ERRORS; payload: ModelErrorType[] }
  | { type: typeof ACTIONS.SENDING_REQUEST }
  | { type: typeof ACTIONS.REQUEST_COMPLETED };

export type State = {
  categories: CategoryType[];
  modelErrors: ModelErrorType[];
  loading: boolean;
};

关键说明

  • 使用typeof ACTIONS获取ACTIONS对象的类型,再通过typeof ACTIONS.SET_CATEGORIES获取对应常量值的字符串字面量类型,这样就能在Action类型定义中合法引用常量对应的类型。
  • 若后续新增action,只需在ACTIONS对象中添加新常量,无需手动修改Action类型定义,类型系统会自动同步更新,避免重复维护。

内容的提问来源于stack exchange,提问作者prajun7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:08:12