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

如何遍历TypeScript桶文件中导出的类型?

如何通过桶导入获取导出类型名称并生成对应类型结构

我希望Key可以是types中任意导出类型的名称,并且能够通过桶导入按名称访问类型。但使用keyof typeof types时,会丢失types中的所有类型,请问这是否可行?

示例文件

types.ts

export type TypeA = {
  a: number;
  b: string;
}

export type TypeB = {
  c: number;
  d: string;
}

index.ts(原写法)

import * as types from './types';

type MyType = Partial<{
  [Key in keyof types]: types[Key][];
}>;

期望结果

type MyType = Partial<{
  "TypeA": TypeA[];
  "TypeB": TypeB[]
}>;

解决方案

这完全可行,问题出在你使用的是值导入——TypeScript中import * as types的typeof types指向模块的运行时命名空间对象,它不包含编译时的类型信息(类型会被擦除)。要获取导出类型的名称和对应类型,需要用类型导入或模块类型查询:

方法1:使用import type(TypeScript 3.8+)

修改index.ts为:

import type * as types from './types';

type MyType = Partial<{
  [Key in keyof types]: types[Key][];
}>;

import type专门用于导入类型,此时types代表模块的类型命名空间,keyof types能正确获取所有导出类型的名称,types[Key]也能准确对应到对应的类型,最终生成的MyType就是你期望的结构。

方法2:使用模块类型查询(兼容旧版本)

如果你的TypeScript版本低于3.8,可以直接查询模块的类型:

type TypesModule = typeof import('./types');
type MyType = Partial<{
  [Key in keyof TypesModule]: TypesModule[Key][];
}>;

这样同样能达到预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:56:03