【问题标题】:Create nested TypeScript type from a simple one从一个简单的类型创建嵌套的 TypeScript 类型
【发布时间】:2019-09-05 10:45:40
【问题描述】:

我有一个看起来像这样的模型

export interface LoremIpsum {

propertyA: string;
propertyB: number;

}

从服务器我有以这种格式返回的数据

{
    "Fields": {
        "propertyA": {
            "value": "something"
        },
        "propertyB": {
            "value": 123
        }
    }
}

这是一种为此创建泛型类型的方法吗?所以我可以像DynamicResponse<LoremIpsum>这样的方式使用它?

【问题讨论】:

    标签: javascript typescript interface


    【解决方案1】:

    您需要使用mapped type 来迭代所有泛型类型T 的键。然后您可以将T 的每个属性类型映射到{ value: T[K] }

    type Fields<T> = {[K in keyof T]: { value: T[K] }};
    
    interface DynamicResponse<T> {
      Fields: Fields<T>
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2019-05-06
      • 2020-01-29
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 2022-01-21
      • 2018-08-14
      • 2021-08-22
      相关资源
      最近更新 更多