Sergey
Sergey

Reputation: 7682

Setter is invoked before constructor

I am trying to create instances of class HelloWorld, however it does not work. I found that problem is that setter methods called instead of constructor which should initialize variable name, while variable welcome is optional.

I specified getters and setters for both variables. Browser's console is throwing an error about maximum call stack size. If I comment my getters&setters it stops throwing errors.

Could anyone explain me that strange behaviour? Also there is another problem with mapping. I'm trying to "return" an array if li elements like in React by using .map(). It gives me the result with commas. How can I get rid of them while printing?

This is a link to my code https://codepen.io/CrUsH20/pen/yzMjzL?editors=1010

Updated #1

I fixed the problem with getters&setters by giving a _ sign for private values.

Now I have a problem with

function print() {
    if (invitations) {
        document.getElementById('result').innerHTML = invitations.map((e)=> {
            return `<li>${e.welcome + e.name}</li>`;
        });
    }
}

Compiler complains that Type 'string[]' is not assignable to type 'string'. in document.getElementById('result').innerHTML while type was not assigned since it is a html element

Update #2

There are solutions: 1# About conflict with constructor and set&get - I changed object's values by adding to their names _. It solved the conflicts. 2# About commas - I added after map .join('') which solved my problem.

Upvotes: 0

Views: 393

Answers (1)

basarat
basarat

Reputation: 276161

The following code (subset of yours) is a compile error:

class HelloWorld {
    constructor(public name: string) {
    }
    set name(e: string) {
        this.name = e;
    }
    get name(): string {
        return this.name;
    }
}

enter image description here

Garbage in => Garbage out

Fix

Dont use getter / setters and properties with the same name.

Upvotes: 1

Related Questions