Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: static method vs function defined outside class

Tags:

typescript

What are the practical differences between a static class method, and a function defined outside a class (at the top of the file) in TypeScript?

I know that there are differences regarding visibilty from other classes and files. When visibility is not a concern though (the function/method is only used in one class), when should we use static methods rather than functions defined outside any classes.

Example:

export class Foo {
  
  constructor(bar: string) {
    Foo.shout(bar);
  }

  private static shout(content: string) {
    console.log(string.toUpperCase());
  }
}

VS

export class Foo {
  
  constructor(bar: string) {
    shout(bar);
  }

}

function shout(content: string) {
  console.log(string.toUpperCase());
}
like image 458
J Heschl Avatar asked Apr 02 '26 11:04

J Heschl


1 Answers

What are the practical differences between a static class method, and a function defined outside a class (at the top of the file) in TypeScript?

Not all that many:

  1. Code using the static method must have access to the class; code using a standalone function must have access to the standalone function instead.

  2. Using the static method technically involves a property lookup on the class's constructor function; using a standalone function doesn't. In practice, this will be optimized such that it doesn't matter.

  3. The code in the static method will have access to the constructor function's parent constructor function via super (something that's fairly unique to JavaScript); code in a standalone function does not (because there is no parent constructor).

  4. Specifically in regard to your example: Your standalone shout function is private to the module in which it appears; the static method on Foo is accessible from other modules that import Foo.

Slightly closer to opinion-land:

  1. A standalone function is standalone, it doesn't provide much context for what it is or where it's defined to someone reading the code. A static method provides more context, via the class name. But, if you're using modules (as you seem to be), the import provides some context for the standalone function.

...when should we use static methods rather than functions defined outside any classes.

That's largely a matter of opinion and style, so off-topic for Stack Overflow. If your team feels the need for consistency using some set of rules, agree a set and be consistent.

like image 66
T.J. Crowder Avatar answered Apr 04 '26 06:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!