0

Is it possible to generate the Json object from interfaces populated with the key type in string? 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?

matera2
  • 3
  • 3
  • You can use static code analysis to generate the objects you need. However, I would suggest you convert them into a standard format, [like json schema](https://www.npmjs.com/package/typescript-json-schema). Another option is to run [TypeDoc on your code using JSON output](http://typedoc.org/guides/development/#json-output) – Ruan Mendes Apr 28 '21 at 14:06
  • See https://stackoverflow.com/questions/45939657/generate-json-schema-from-typescript – Ruan Mendes Apr 28 '21 at 14:18

1 Answers1

0

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..

Dus
  • 4,052
  • 5
  • 30
  • 49