0

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

1 Answer 1

3

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.

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

3 Comments

I was writing same thing
@Suren Srapyan - I agreed with you. But what is the reason the class keeping the static like this? any special requirement or reason? what is the correct use of static ? can you please and in your answer?
static should be those fields that are not related to each object. For example, you can have a Point class, which has a static method with name addPoints. This can accept Point objects, add them together and return that. Because this method is related to Points, from the encapsulation view you can make it as static and put in the Point class

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.