如何索引一个特定的数组元素在Typescript?



我想创建一个类型,它将数组中一个对象的两个属性的值组合在一起。

到目前为止,我的解决方案是这样的:
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}']索引该类型,以创建映射类型内所有元素的联合。

游乐场