Issue
I am new to Angular. I took the following example from a book, to get familiar with javascript classes. I try to load it using main.ts . However, I get the following error: error TS2551: Property '_weather' does not exist on type 'MyClass'. Did you mean 'weather'? Can anybody explain me why? It should work, it is a copy/paste from a book. I can make it work if I manually add _weather: string; and name: string; declarations. But it shouldn't be necessary.
 class MyClass {
        constructor(name, weather) {
            this.name = name;
            this._weather = weather;
        }
        set weather(value) {
            this._weather = value;
        }
        get weather() {
            return `Today is ${this._weather}`;
        }
        printMessages() {
            console.log("Hello " + this.name + ". ");
            console.log(this.weather);
        }
    }
    let myData = new MyClass("Adam", "sunny");
    myData.printMessages();
                            Solution
Error is self explained.
error TS2551: Property '_weather' does not exist on type 'MyClass'. Did you mean 'weather'?
In your code snippet you are trying to assign value to the property that don't exists.
this._weather is arranged to be private since you create setter/getter to it.
In typescript you should name private variables with underscore in order to avoid duplicates
class MyClass {
    private _weather: any;
    private _name: any;
    constructor(name: any, weather: any) {
        this.name = name;
        this.weather = weather;
    }
    set name(value) {
        this._name = value;
    }
    get name() {
        return `Name is ${this._name}`;
    }
    set weather(value) {
        this._weather = value;
    }
    get weather() {
        return `Today is ${this._weather}`;
    }
    printMessages() {
        console.log("Hello " + this.name + ". ");
        console.log(this.weather);
    }
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();
If you don't want to specify setters/getters then write constructor like so
In this case Typescript will automatically generate thore properties.
class MyClass {
    constructor(private name: any, private weather: any) {}
    printMessages() {
        console.log("Hello " + this.name + ". ");
        console.log(this.weather);
    }
}
let myData = new MyClass("Adam", "sunny");
myData.printMessages();
Answered By - user12251399
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.