【问题标题】:TypeScript: populate JSON object with each key type in string based on the interfaceTypeScript:根据接口使用字符串中的每个键类型填充 JSON 对象
【发布时间】:2021-07-13 12:38:18
【问题描述】:

是否可以从用字符串中的键类型填充的接口生成 Json 对象? 参见下面的接口示例:

export interface shop {
    refNo: Number
    domain?: string[],    
    details: {
        name? : string,
        cui : string,
        contact?: {
            name?: string,
            phone?: string
        }[]
    }

这应该是结果:

let shopObj = { 
    refNo: "Number"
    domain?: ["string"], // "Array String"   
    details: {
        name? : "string",
        cui : "string",
        contact?: [{
            name?: "string", 
            phone?: "string"
        }]
    }
}

是否有任何实用程序可以执行此操作,有人知道如何从界面完成此转换吗?

【问题讨论】:

标签: javascript node.js json typescript interface


【解决方案1】:

你试图做的事情是不可能的,因为接口是类型而不是值,所以你不能把它当作一个值..

您唯一能做的就是启动一个变量,然后使用typeof 提取每个字段的类型,但这与您想要实现的目标相差甚远,而且它非常弯曲且非常丑陋..

【讨论】:

  • 你可以使用静态代码分析来做OP想要的。
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 2020-09-11
  • 2020-11-04
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 2021-03-28
  • 2017-05-07
相关资源
最近更新 更多