0

Say we have:

class MyClass {
  myProperty: string
}

Is there any built in function or easy way to get JSON like this?:

{
  "myProperty": "string"
}

EDIT: My end goal is I want to dynamically print typed class definitions to a web view, in some kind of structured object syntax like JSON. I'm trying to make a server API that will return the schema for various custom classes - for example http://myserver.com/MyClass should return MyClass's properties and their types as a JSON string or other structured representation.

2 Answers 2

1

Evert is correct, however a workaround can look like this

class MyClass {
  myProperty: string = 'string'
}

JSON.stringify(new MyClass) // shows what you want

In other words, setting a default property value lets TS compile properties to JS

If the above solution is not acceptable, then I would suggest you parsing TS files with your classes with https://dsherret.github.io/ts-simple-ast/.

Sign up to request clarification or add additional context in comments.

2 Comments

This code returns {"myProperty":""} which is not what I want. What I want is {"myProperty":"string"}. Additionally, if myProperty was a number it should return {"myProperty":"number"} not {"myProperty":0} (for example).
Sorry, I missed that part. I've updated my answer and supplied a solution (not very straight-forward one, but not too hard)
1

Typescript class properties exist at build-time only. They are removed from your source after compiling to .js. As such, there is no run-time way to get to the class properties.

Your code snippet compiles to:

var MyClass = /** @class */ (function () {
    function MyClass() {
    }
    return MyClass;
}());

As you can see, the property disappeared.

Based on your update, I had this exact problem. This is how I solved it.

  1. My JSON-based API uses json-schema across the board for type validation, and also exposes these schemas for clients to re-use.
  2. I used an npm package to automatically convert json-schema to Typescript.

This works brilliantly.

1 Comment

In you situation I would figure out why you need it, and based on that see if there's a more elegant solution. It's hard to tell from your question what your end-goal is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.