如何程序化合并TypeScript导出类型为联合类型?
程序化创建导出类型的联合类型方案
当然有更高效的办法!你完全不用手动罗列每个类型来创建联合类型,利用TypeScript的类型系统特性就能实现类似「自动合并所有导出类型」的效果,跟你想要的Array#join思路类似,只是针对类型层面的操作。
方法一:在导入文件中自动生成联合类型
原理是先获取整个模块的类型,再提取所有导出类型的联合:
首先是你的myTypes.ts代码(保持不变):
// myTypes.ts export type Foo = { foo: string } export type Bar = { bar: string } export type Baz = { baz: string }
然后在otherFile.ts里这么写:
// otherFile.ts import * as types from './myTypes.ts' // 自动生成所有导出类型的联合类型 type MyUnion = typeof types[keyof typeof types]
这里的typeof types会拿到整个模块的类型结构,keyof typeof types获取所有导出的类型名称(也就是"Foo" | "Bar" | "Baz"),最后通过typeof types[keyof typeof types]就把所有对应的类型合并成了联合类型,完全不需要手动维护成员列表。
方法二:在源文件中预定义联合类型导出
如果希望其他文件能直接导入这个联合类型,不用每次都写类型逻辑,可以在myTypes.ts里提前定义好:
// myTypes.ts export type Foo = { foo: string } export type Bar = { bar: string } export type Baz = { baz: string } // 自动生成并导出所有类型的联合 export type AllTypesUnion = typeof import('./myTypes.ts')[keyof typeof import('./myTypes.ts')]
之后在其他文件里直接导入即可:
// otherFile.ts import { AllTypesUnion as MyUnion } from './myTypes.ts'
额外处理:过滤非类型导出
如果你的myTypes.ts里除了类型还导出了变量、函数等,上面的方法会把这些值的类型也包含进去。这时可以用Extract工具类型过滤出仅对象类型(也就是我们定义的接口/类型):
// otherFile.ts import * as types from './myTypes.ts' // 只保留对象类型的联合 type MyUnion = Extract<typeof types[keyof typeof types], object>
这样不管后续你在myTypes.ts里新增多少类型,联合类型都会自动更新,完全实现了程序化的合并效果。
内容的提问来源于stack exchange,提问作者renegadeborealis
相关产品推荐
相关产品推荐

