简体   繁体   English

TypeScript:根据接口使用字符串中的每个键类型填充 JSON object

[英]TypeScript: populate JSON object with each key type in string based on the interface

Is it possible to generate the Json object from interfaces populated with the key type in string?是否可以从用字符串中的密钥类型填充的接口生成 Json object? See below the interface example:见下面的接口示例:

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

This should be the result:这应该是结果:

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

are there any utilities that do this, does anyone have any idea how this transformation can be done from the interface?是否有任何实用程序可以做到这一点,有没有人知道如何从界面完成这种转换?

What you're trying to do is impossible, since interfaces are types and not values, so you can't treat it as a value..您尝试做的事情是不可能的,因为接口是类型而不是值,因此您不能将其视为值..

The only thing you can do, is initiate a variable and then extract the type of each field by using typeof , but its very off from what you're trying to achieve, and its very crooked and quite ugly..您唯一能做的就是启动一个变量,然后使用typeof提取每个字段的类型,但这与您想要实现的目标非常不同,而且它非常弯曲且非常丑陋..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM