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

TypeScript中能否声明可通过点符号访问的嵌套类型分组?

实现方案说明

这个需求完全可以在TypeScript中实现,核心是利用TypeScript原生的**命名空间(namespace)**特性,支持通过点语法直接访问嵌套的子类型。

方案1:纯类型场景(仅需通过FuncA访问子类型,无需作为值使用)

直接在types.ts中导出命名空间即可,代码示例如下:

// types.ts
export namespace FuncA {
  // 自定义你的Param1类型
  export type Param1 = string | number;
  // 自定义你的Param2类型
  export type Param2 = {
    id: number;
    extra?: Record<string, any>;
  };
  // 自定义你的Response类型
  export type Response = {
    code: number;
    data: FuncA.Param2[];
    message: string;
  };
}

export namespace FuncB {
  export type Param = {
    page: number;
    pageSize: number;
    filters?: Record<string, any>;
  };
  export type Response = {
    total: number;
    list: Record<string, any>[];
  };
}

该方案写法最简洁,完全匹配你示例中的调用写法,无需额外配置。

方案2:需要FuncA同时作为值/基础类型 + 子类型容器的场景

如果需要FuncA本身也是一个可用的类型(比如函数类型),可以利用TypeScript的同名声明合并特性,将基础类型和命名空间绑定:

// types.ts
// 定义FuncA本身的基础类型,比如函数类型
export type FuncA = (p1: FuncA.Param1, p2: FuncA.Param2) => FuncA.Response;
// 同名命名空间挂载子类型
export namespace FuncA {
  export type Param1 = string | number;
  export type Param2 = { id: number; name: string };
  export type Response = { code: number; data: FuncA.Param2[]; msg: string };
}

export type FuncB = (p: FuncB.Param) => Promise<FuncB.Response>;
export namespace FuncB {
  export type Param = { page: number; pageSize: number };
  export type Response = { total: number; list: any[] };
}

注意事项

如果你开启了isolatedModules配置(绝大多数前端工程脚手架如Vite、Create React App默认开启),导出纯类型命名空间时可能会触发"导出值未使用"的警告,可以将导出写法改为export type { FuncA, FuncB }即可消除警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:27:06