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

TypeScript中是否可以创建可层级索引访问的子类型?

实现方案

完全可以实现你要的层级索引类型效果,常见有两种实现方式:

方式1:嵌套命名空间(最贴合你的示例用法)

这种方式可以直接通过.语法层级访问类型,和你给出的示例写法完全一致:

// 定义层级类型
namespace Actions {
  export namespace User {
    export type Add = {
      type: "user/add";
      payload: {
        name: string;
        age: number;
      };
    };
    export type Remove = {
      type: "user/remove";
      payload: {
        userId: number;
      };
    };
  }
  // 可继续扩展其他业务模块的类型
  export namespace Order {
    export type Create = {
      type: "order/create";
      payload: {
        orderNo: string;
        amount: number;
      };
    };
  }
}

// 使用方式和你给出的示例完全匹配
const addUserAction: Actions.User.Add = {
  type: "user/add",
  payload: { name: "张三", age: 20 },
};
const removeUserAction: Actions.User.Remove = {
  type: "user/remove",
  payload: { userId: 1001 },
};

如果不需要生成运行时代码,只保留类型定义,可以在namespace前加declare关键字,也能适配开启isolatedModules配置的项目:

declare namespace Actions {
  // 内部定义和上面一致
}

方式2:嵌套类型别名

如果不想用命名空间,也可以通过嵌套的type定义,使用时通过索引访问语法取值:

type Actions = {
  User: {
    Add: {
      type: "user/add";
      payload: { name: string; age: number };
    };
    Remove: {
      type: "user/remove";
      payload: { userId: number };
    };
  };
};

// 使用时通过索引访问类型
const addUserAction: Actions["User"]["Add"] = {
  type: "user/add",
  payload: { name: "张三", age: 20 },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 02:15:03