简体   繁体   中英

Exists any way to generate JSON declaration from a typescript class?

Example

class A {
       constructor(public val1: number, public val2: number,public val3: string, public b: B) {
 }
}

class B {
       constructor(public val4: boolean, public val5: number) {
 }
}

exists any function that receives class A and return the JSON structure of the class, not matter if it's just visual, return this:

{val1: number, val2: number, val3: string, b: {val4: boolean, val5: number}}

a class in typescript it's no more that a hash of {nameProperty:data type, ...}

I want the class that only have properties, has not methods.

I'll better explain what I wrote in my comment.

In typescript when you define a class you need to define the members in it, but when it's compiled to js the members aren't really being added to the class.

Consider the following typescript:

class A {
    str: string;
    num: number;
}

It compiles to:

var A = (function () {
    function A() {
    }
    return A;
}());

As you can see there's no trace of the str and num members in the js code.
When you assign values:

class A {
    constructor(public str: string, public num: number) {}
}

It compiles to:

var A = (function () {
    function A(str, num) {
        this.str = str;
        this.num = num;
    }
    return A;
}());

Here you can see str and num , but notice that they are added to the instance in the constructor, they are not added to the prototype (unlike methods) or to A , so there's no way to access them until you have an instance.

Because of that you can not get a mapping of properties in a class.
You can use the reflect-metadata package to save the members meta data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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