-2

Say I have a typescript file containing the following:

// my-ts-file.ts
const inner = {
  hello: "world",
};

export const value = {
  prop1: "hello",
  prop2: "world",
  prop3: 42,
  prop4: inner,
}

When I hover over this code in vscode, typescript correctly infers the type of the value variable as the following:

const value: {
    prop1: string;
    prop2: string;
    prop3: number;
    prop4: {
        hello: string;
    };
}

Now, assume I want to write a separate program that reads the contents of my-ts-file.ts above and parses + returns / converts the type of the exported const value as a JSON such as the following:

{
    "prop1": "string",
    "prop2": "string",
    "prop3": "number",
    "prop4": {
        "hello": "string"
    }
}
  

Is this possible? And how would I go about doing this? What libraries / packages would make this possible.

01101010
  • 81
  • 1
  • 7
  • 1
    Have a look at: https://stackoverflow.com/questions/45939657/generate-json-schema-from-typescript – spikef Jun 01 '23 at 12:07
  • Just parse it with `typescript`, walk the AST, find your node and getTypeChecker can be used to directly print ` { prop1: string; prop2: string; prop3: number; ....}` If you actually want "string" then just write your customer parser for that typeinfo on that node. – Istvan Tabanyi Jun 01 '23 at 12:22
  • You can simply parse the code with `JSON.parse` as mentioned below. No need of any libraries. – Keygun2k1 Jun 01 '23 at 12:25

1 Answers1

-1

Before anything, be aware what you are expecting as a result is not a valid JSON. In JSON format, keys are supposed to be strings.

Doing this should do the trick for you :

JSON.parse(JSON.stringify(value))
matreurai
  • 147
  • 12
  • Yep thanks. I fixed the invalid JSON, oversight on my part. But, I need to be able to do this from a separate program that just looks at the source files. I don't actually have the `value` variable in memory anywhere. – 01101010 Jun 02 '23 at 12:58
  • Was there any specific reason why you need to read the .ts file containing the source code instead of simply stocking the JSON data in a .json file and read and write to it using a dataset ? Because if you are simply trying to read the file and parse it, you'll have to use regex to string parse the file. I am not sure this is a good design choice, except if you have a very specific need for it, and if so, I'd like to know what it is to better help you resolve your issue. – matreurai Jun 05 '23 at 12:56