如何动态生成 TypeScript 接口中对象声明的键?

Bor*_*dev 0 typescript

假设我们有一个具有以下键的对象:(键的数量始终为 30)

const options = {
  "option1": 582, // Random value
  "option1": 6,
  "option3": 123,
  "option4": 3812,
  // ...
  "option30": 482,
}
Run Code Online (Sandbox Code Playgroud)

因此,为该对象声明接口的方法之一是以下示例:

interface IProperties {
  "option1": number,
  "option2": number,
  "option3": number,
  "option4": number,
  // ...
  "option30": number
} 
Run Code Online (Sandbox Code Playgroud)

但如果选项多于 30 个怎么办?(例如 1000)编写一个有 1000 个键的接口是很愚蠢的。

那么,对于这种情况,哪个是最好的解决方案呢?我们如何在界面中动态生成密钥而不是硬编码?也许我们可以在循环中生成密钥?

sko*_*ovy 5

一种方法是定义一个类型,Numbers该类型是您想要包含的范围内所有数字的并集(例如:1 - 30)。该联合仍然需要详尽地列出全部数字范围,但允许定义更动态的Properties类型。

然后,使用模板文字来定义所有可能的键。

// The non-unique prefix for all option keys
type Prefix = "option"

// Exhaustive list of all options
type Numbers = 0 | 1 | 2 | 3 | 4 | 5

// Combine the prefix and numbers using a template literal
type Keys = `${Prefix}${Numbers}`

// Equivalent to:
//
// type Keys = "option0" | "option1" | "option2" | "option3" | "option4" | "option5"

type Properties = {
    [Key in Keys]: number
}

// Equivalent to:
//
// type Properties = {
//     option0: number;
//     option1: number;
//     option2: number;
//     option3: number;
//     option4: number;
//     option5: number;
// }
Run Code Online (Sandbox Code Playgroud)

TypeScript 游乐场

假设它们Numbers是“固定的”,您可以在控制台中使用一段 JavaScript 来创建完整的Numbers类型联合。

[...Array(30).keys()].map(key => key + 1).join(" | ")
// "1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30"
Run Code Online (Sandbox Code Playgroud)

然后可以将其复制并粘贴为类型的值Numbers