Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there benefits in using the static modifier on functions in TypeScript?

I recently started working with TypeScript and my IDE WebStorm linted me that I could use a static modifier...

export default class MyClass {
    public bar(): any {
        // do sth. with instance values
    }

    private foo(a: any, b: any): any {
        // do sth. without instance values, like checking
    }
}

Here I would get a warning that foo(a, b) could be declared static. For now I turned that "warning" off, since I mostly consider liberal use of static as "code-smell", but then again I'm not an expert in TypeScript.

Are there any significant "side-benefits" of using the static modifier? Besides what it does per definition.

like image 795
Rüdiger Avatar asked Apr 20 '16 12:04

Rüdiger


1 Answers

Like you alluded to, using the static modifier has the main benefit of making class members accessible without having to instantiate the class.

A noteworthy "side-effect" of using a static modifier on a class member in TypeScript is that you will not be able to access that member from a class instance.

class Hamburger {
     static beef_percentage: number = 75;
     public tasty: boolean = false;
}

console.log(Hamburger.beef_percentage); // 75
console.log(Hamburger.tasty); // Error

var myHamburger = new Hamburger();
console.log(myHamburger.beef_percentage); // Error
console.log(myHamburger.tasty); // false

I suppose that this could be useful in some instances.

If a method is not accessing members from a its instance I recommend making that method static for the sake of clarity concerning the purpose of your class.

like image 149
Chris Bier Avatar answered Oct 18 '22 07:10

Chris Bier