3gwebtrain
3gwebtrain

Reputation: 15293

How to get value from static method in typescript?

In my typescript, there is a method added in static. later I am trying to call the same. But getting error... while compile the code. anything wrong with my code? any one help me to understand the static properties in typescript?

Here is my code :

class Car { 
    private distanceRun: number = 0;
    color: string;

    constructor(public hybrid:boolean, color:string="red") {
        this.color = color;
    }

    getGasConsumption():string { 
        return this.hybrid ? "Low" : "High";
    }

    drive(distance:number) {
        return this.distanceRun += distance;
    }

    static horn():string {
        return "HOOONK!";
    }

    get distance():number {
        return this.distanceRun;
    }

}

let newCar = new Car(false);
console.log(newCar.color);
console.log(newCar.horn()); //shows error as Property 'horn' does not exist on type 'Car'..

Live

Upvotes: 0

Views: 374

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

Static members are not attached to the instances of the class. They are attached to the class itself.

You need to call static methods and properties via class, not it's intance - like thisCar.horn().

Live example

You can see, that

class Test {
   get() { 

   }

   static getStatic() {

   }
}

is compiled into this

function Test() {

}

Test.prototype.get = function () {

};

Test.getStatic = function () {

};

From this it is obvious that getStatic is in the Test itself, while get is in the prototype of the Test, which will be referenced from the objects, created via Test function-constructor.

Upvotes: 3

Related Questions