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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With