问题声明
我想声明mapper1
,使其值只能为Type1
,并声明mapper2
,使其值只能为Type2
。我该如何在不声明键类型的情况下实现这一点?
背景
在TypeScript中,我有:
import Bar1 from './bar1'; // Type1
import Bar2 from './bar2'; // Type1
import Bar3 from './bar3'; // Type2
import Bar4 from './bar4'; // Type2
const mapper1 = {
foo1: bar1,
foo2: bar2,
} as const;
const mapper2 = {
foo3: bar3,
foo4: bar4,
} as const;
export type MapperKeys = keyof typeof mapper1 | keyof typeof mapper2;
"bar1"和"bar2"具有相同的类型("Type1")。"bar3"和"bar4"具有相同的类型("Type2")。"Type1"与"Type2"不同。
"MapperKeys"是"mapper1"和"mapper2"键的并集('foo1' | 'foo2' | 'foo3' | 'foo4')。
我尝试过的方法
方法1:
const mapper1: Record<string, Type1> = {
foo1: bar1,
foo2: bar2,
} as const;
const mapper2: Record<string, Type2> = {
foo3: bar3,
foo4: bar4,
} as const;
但现在MapperKeys
是'string'
。我希望它成为mapper1
和mapper2
键的并集('foo1' | 'foo2' | 'foo3' | 'foo4'
)。
方法二:
const mapper1: Record<'foo1' | 'foo2', Type1> = {
foo1: bar1,
foo2: bar2,
} as const;
const mapper2: Record<'foo3' | 'foo4', Type2> = {
foo3: bar3,
foo4: bar4,
} as const;
这个可以用,但不是DRY。
Record<string, Type1>
,那么您可以稍后编写mapper1.someOtherKey = bar1
,因此编译器无法确定mapper1
的类型仅具有键"foo1"
和"foo2"
。)如果您想要推断和约束检查,可以编写一个通用的帮助函数来实现,如我上面的链接所示。如果这有意义,我可以写出一个答案;如果没有,那么我错过了什么? - jcalz