【问题标题】:How to dynamic generates keys for object declaration in interface in TypeScript?如何在 TypeScript 的接口中动态生成对象声明的键?
【发布时间】:2021-08-14 21:20:44
【问题描述】:

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

const options = {
  "option1": 582, // Random value
  "option1": 6,
  "option3": 123,
  "option4": 3812,
  // ...
  "option30": 482,
}

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

interface IProperties {
  "option1": number,
  "option2": number,
  "option3": number,
  "option4": number,
  // ...
  "option30": number
} 

但是如果选项超过 30 个呢? (例如 1000 个) 写一个有 1000 个键的接口会很傻。

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

    然后,使用tempalte literal 定义所有可能的键。

    // 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;
    // }
    

    TypeScript playground

    假设 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"
    

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

    【讨论】:

      【解决方案2】:

      您正在寻找Record<T,K>

      【讨论】:

        猜你喜欢
        • 2021-09-16
        • 2021-05-21
        • 2020-02-24
        • 1970-01-01
        • 1970-01-01
        • 2017-02-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-14
        相关资源
        最近更新 更多