我想创建一种类型,将一个对象的两个属性值组合到一个数组中。
到目前为止我的解决方案如下所示:
const CONFIGS = [
{ section: "a", name: "1" },
{ section: "b", name: "2" },
] as const;
type ConfigSections<I extends number> = typeof CONFIGS[I]["section"];
type ConfigSectionEntryName<I extends number> = typeof CONFIGS[I]["name"];
// Allows all permutations of section and name: "a_1" | "a_2" | "b_1" | "b_2" :(
// I only want "a_1" | "b_2"
type CompleteConfigName<I extends number> =
`${ConfigSections<I>}_${ConfigSectionEntryName<I>}`;
但是在类型 CompleteConfigName<I extends number>
中I
似乎允许任何数字,因为类型解析为 "a_1" | "a_2" | "b_1" | "b_2"
。
但我想强制执行特定的索引号 I
,这样类型结果为 "a_1" | "b_2"
最佳答案
您应该使用如下所示的映射类型:
type CompleteConfigName = {
[K in keyof typeof CONFIGS]: (typeof CONFIGS)[K] extends {
section: infer A, name: infer B
}
? `${A & string}_${B & string}`
: never
}[keyof typeof CONFIGS & `${bigint}`]
CompleteConfigName
映射元组中的每个元素以创建字符串文字。我们可以用[keyof typeof CONFIGS & '${bigint}']
来索引这个类型创建映射类型内所有元素的并集。
关于typescript - 如何在 Typescript 中索引特定数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72447121/