If TypeScript compiles down to JavaScript and JavaScript is often viewed as not having classes, then how can TypeScript incorporate static methods?
Contrary to popular belief, JavaScript does have a way to define classes. You can refer to this documentation on classes in JavaScript
The confusion might stem from the fact that JavaScript didn't always support classes natively. However, even before official class support was added, it was possible to simulate class-like behavior using the prototype-based system. This distinction doesn't matter much now, as all modern JavaScript engines provide support for the class
keyword.
In object-oriented programming languages that have class support, a static method is a method belonging to the class itself rather than to instances of the class.
This means that the static method is inherent to the class structure and is available irrespective of any particular instance being created.
A class acts as a blueprint or template containing information necessary for creating instances during runtime, and a static method is a fundamental part of this blueprint.
To clarify, a static method is not directly accessible by instances but is instead associated with the constructor function that produces instances.
For example, if you had a class called Person
with a static method to retrieve all person records from a database, individual instances of Person
would not handle this operation. Instead, it pertains to the concept of the overall collection of Person
objects, rather than any specific instance.
Hence, static methods are not intrinsic to individual instances, but rather belong to the constructor function.
In essence, a class
serves as a creator of objects with similar characteristics and behaviors, while a static
member within that class represents a value tied to the constructor function rather than instances themselves.
Consider this example of a static method named findAll
:
class Person {
static async findAll(): Promise<Person[]> { ... }
instanceMethod() { ... }
}
const people = await Person.findAll()
new Person().instanceMethod
A similar concept applies here:
function Person() {
return this.name = 'Foo'
}
Person.prototype.instanceMethod = () => { ... }
Person.findAll = async (): Promise<Person[]> => { ... }
const people = await Person.findAll()
new Person().instanceMethod
In both cases, there exists a constructor capable of generating instances with instance methods, along with a static method associated with the constructor itself.
Adding the static
keyword makes the method accessible through the constructor, rather than through instances.