liveBook · Manning

Static method

As explained in Essential TypeScript 5, Third Edition

A static method is a method defined on a constructor function and accessed through the constructor rather than through its instances.

A static method belongs to a constructor function or class, so callers access it through that constructor rather than through an object instance. Use it for operations that work with supplied objects but do not require one particular instance. section 4.2.6 section 4.2.7

JavaScript constructor function

A function is an object, so JavaScript permits a method to be assigned directly to it. Product.process accepts several products and invokes each product's instance toString method. Call it as Product.process(...), not product.process(...). section 4.2.6

Class syntax expresses the same distinction with the static keyword. TaxedProduct.process is called through the class, while toString and getPriceIncTax are called on each TaxedProduct object. A static method can still process instance methods on objects it receives. section 4.2.7

Keep these access rules in mind:

  • Call a static method through its constructor or class, such as TaxedProduct.process(...). section 4.2.7
  • Do not expect a static method to appear on instances; instance methods and static methods occupy different access paths. section 4.2.6
  • Give a static method its own generic type parameters when it must operate on varying typed data. section 12.3.8

Static methods on generic classes

DataCollection<T> has instance members associated with T, but its static reverse method is accessed as DataCollection.reverse(cities). Declaring reverse<ArrayType> gives the method its own type parameter, independent of the class's T. section 12.3.8

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains constructor and class syntax, invocation boundaries, and independent generic parameters through runnable examples.
Examples
Demonstrates Product.process, TaxedProduct.process, and DataCollection.reverse with JavaScript objects and typed collections.
What it assumes
Assumes familiarity with JavaScript objects, functions, classes, and instances; develops the class-level versus instance-level distinction.
What you can do after
Apply it by defining and invoking constructor-level operations in JavaScript classes and generic TypeScript classes.
How it connects
Connects static methods with constructor functions, classes, instance methods, inheritance, and generic types.

Also explained in

Compare how 5 books explain static method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.