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

3
  • 1
    Have a look at: stackoverflow.com/questions/45939657/… Commented Jun 1, 2023 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. Commented Jun 1, 2023 at 12:22
  • You can simply parse the code with JSON.parse as mentioned below. No need of any libraries. Commented Jun 1, 2023 at 12:25

1 Answer 1

-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))
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.