typescript - 如何在 Typescript 中索引特定数组元素?

标签 typescript types typescript-types

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

到目前为止我的解决方案如下所示:

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

关于typescript - 如何在 Typescript 中索引特定数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72447121/

相关文章:

javascript - 在 Angular2 中通过服务向组件添加 css,这可能吗?

typescript - @types/mssql - 即使 TS 在正确的位置查找,也找不到连接池类型定义

TypeScript:如何为具有许多相同类型的键和相同类型的值的对象创建接口(interface)?

typescript - 为什么映射类型中与可区分联合的交集会给出所有类型的联合而不是缩小它?

angular - 如何在 Angular 中引用和使用另一个模块中的组件?

javascript - 如何过滤可能是几个树级别深度的父子数组的多个属性

Angular 2 & RxJs catch 函数回调绑定(bind)到 'this' 导致 http 请求一遍遍重复

c++ - char16_t 和 char32_t 是 std 命名空间的一部分吗?

haskell - 为什么有些运算符在赋值时会改变类型?

兼容的结构类型