如何索引 Typescript 中的特定数组元素?

How to index a specific array element in 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}'] 索引此类型以创建映射类型内所有元素的联合。

Playground