Typescript:从模块/对象的值推断联合类型



我正在寻找一种在typescript中实现类似keyof typeof myModule的方法。但是,我寻找的不是键字符串的并集,而是值类型的并集。

我有一个模块,导出越来越多的项目-

myModule.ts:

export const Thing1;
export const Thing2;
export const Thing3;
// ... many more things!

这个模块是在其他地方导入的,我想构造一个联合类型是Thing1 | Thing2 | Thing3 | ...,但不手动这样做。

anotherModule.ts:

import * as things from './myModule';
type AnyThingKey = keyof typeof things;
function useThings(thing: /* AnyThing - this is where/how I'd use the union type */) {
// ... do things ...
}

是否有一种公认的方法来完成这一点?

我想你就快找到答案了。

你的anotherModule.ts应该看起来像这样:

import * as things from './myModule';
type AnyThingKey = typeof things[keyof typeof things];
function useThings(thing: AnyThingKey) {
// ... do things ...
}
useThings("Thing1"); // OK
useThings("foo");    // compiler error

最新更新