0

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.

3
  • That's incorrect, classes in typescript do have (or can have) functions (which are then methods), and they are not just "a hash of {nameProperty:data type, ...}", maybe you are referring to interfaces. In your example the classes don't even have any members (you'll need to add public for the args to be members). And even if you did, the properties of a class aren't part of the prototype, only the instance so you can't get them form a class. Commented Mar 24, 2017 at 17:23
  • I am sorry you are right, I have will add public to all properties, I forget it Commented Mar 24, 2017 at 17:28
  • I know that classes in typescript can have functions, but I say that my class only will have properties, I'm sorry for my english Commented Mar 24, 2017 at 17:41

1 Answer 1

1

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.

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

2 Comments

I understand, there is not way of get data type of properties and represent it in hash
I find this extension for vscode with that functionality, marketplace.visualstudio.com/…, it does with interfaces but is very useful.

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.