TypeScript Static Methods Tutorial
In this TypeScript tutorial we learn about static methods that belong to a class, instead of an instance of a class.
We cover the 'static' keyword, how to define and invoke them as well as what happens when static methods have the same name.
- What is a static class method
- How to define a static class method
- How to call a static class method
- Static class methods with duplicate names
- Static class properties
- A note on 'this' in static methods
- Does TypeScript have static classes
- Use static methods for utility
- Further Reading
- Summary: Points to remember
note
The examples in this lesson should be compiled with the compiler flag
--target es6
or higher.
What is a static class method
A static class method is a method that belongs to the class itself, not the instance of a class.
That means we don’t need an object to call a static class method. We call them directly from the class itself.
As an example, let’s consider a class called Person . Our Person has an age property and a birthday() method that increases the age by 1.
Typically, we would need to instantiate a new object to be able to access the method.
class Person {
age = 28
birthday() {
this.age += 1
console.log("Hooray! Im, " + this.age)
}
}
// instantiate
var p1 = new Person()
// access method
p1.birthday()
Now the birthday() method belongs to the p1 object instance. So what does that mean?
It means that the method can only operate on the p1 object. p1 could never affect the age of p2 .
A static method belongs to the class itself and it could potentially affect the ages of both p1 and p2 . Because it belongs to the class, we have to invoke it directly on the class, not on an object.
// access method
Person.birthday();
How to define a static class method
To define a static class method, we use the static keyword in front of a method definition in a class.
static method_name() {
// body
}
class Person {
static walk() {
console.log("Walking...")
}
}
Static methods and access modifiers
TypeScript allows us to encapsulate our static methods with access modifiers, just like regular methods.
To do this, we specify one of the following three access modifiers before the static keyword.
- public
- private
- protected
public static method_name() {}
private static method_name() {}
protected static method_name() {}
note The public modifier is the default and doesn’t have to be specified explicitly.
public static method_name() {}
// is the same as
static method_name() {}
How to call a static class method
As we’ve mentioned before, a static method doesn’t need an object in order for us to use it. It can be called directly from the class with dot notation.
class Person {
static walk() {
console.log("Walking...")
}
}
// invoke method directly
// from the 'Person' class
Person.walk()
In the example above, we invoke the method without creating an object. If we compile and run the script, it will print the “Walking…” text to the console.
Static class methods with duplicate names
In Javascript, we may have as many static class methods as we need, even ones with similar names.
If we do have static methods with similar names, the compiler will always invoke the last one.
<script>
class Person {
static walk() {
document.write("Walking first...")
}
static walk() {
document.write("Walking last...")
}
}
Person.walk()
</script>
In the Javascript example above, the translator will run the second walk() method.
But, in TypeScript this isn’t allowed, the compiler will raise an error.
main.ts:3:10 - error TS2393: Duplicate function implementation.
3 static walk() {
~~~~
main.ts:7:10 - error TS2393: Duplicate function implementation.
7 static walk() {
~~~~
Static class properties
We are not limited to using only static methods. TypeScript allows us to declare our properties as static as well.
Static properties are also defined with the static keyword in front of the property name, and are accessed directly on the class with dot notation.
class Person {
static age = 28
}
console.log(Person.age)
Static methods can mutate static properties
At the start of the lesson we mentioned that a static method could potentially affect a static property. Well it’s true, but only if that property is also static.
We’ll use the birthday example from before. But this time we’ll make the method static and try to invoke it on the class.
class Person {
age = 28
static birthday() {
this.age += 1
console.log("Hooray! Im, " + this.age)
}
}
Person.birthday()
If we try to compile the script, TypeScript will raise the following error.
Property 'age' does not exist on type 'typeof Person'.
That’s because age is instance property, it belongs to an object and cannot be affected outside of that object.
For the static method to be able to change the age , we have to declare it as static too.
class Person {
static age = 28
static birthday() {
this.age += 1
console.log("Hooray! Im, " + this.age)
}
}
Person.birthday()
When we compile and run the example above, it will show the age in the console.
Static members can't be accessed by object instances
TypeScript doesn’t allow a static property or method to be affected by an object instance.
class Person {
static age = 28
static birthday() {
this.age += 1
console.log("Hooray! Im, " + this.age)
}
}
var p1 = new Person()
p1.age
p1.birthday()
We can instantiate the object just fine, but if we try to access the property or method, TypeScript will raise an error.
Property 'age' is a static member of type 'Person'
Property 'birthday' is a static member of type 'Person'
A note on 'this' in static methods
Normally when we use the this construct, it refers to the calling object. But when we use this with a static member, it refers to the class.
Does TypeScript have static classes
No, because there’s really no need for them.
Languages like C# or Java force us to define all our data and methods to be inside a class. But TypeScript doesn’t have such a restriction, so a regular object or top-level function will do the job just as well.
class Person {
static birthday() {}
}
function birthday() {}
const UtilObject = {
birthday() {}
}
Use static methods for utility
In a real world situation, static methods would typically be used for helper, or utility methods.
Let’s see an example that checks if a string contains a given word and returns true if it does.
// Test string
let txt: string = "Lorem ipsum dolor sit amet."
// Static method
export class Util {
// Does a string contain a given substring
public static contains(str: string, substr: string) {
return str.indexOf(substr) !== -1
}
}
console.log( Util.contains(txt, 'sit') )
But as mentioned before, we can use objects or top-level functions to accomplish the same thing.
// Test string
let txt:string = "Lorem ipsum dolor sit amet."
// Static method
export class Util {
public static contains(str: string, substr: string) {
return str.indexOf(substr) !== -1
}
}
console.log( Util.contains(txt, 'sit') )
// Preferred 1: Top-level function
function contains(str: string, substr: string) {
return str.indexOf(substr) !== -1
}
console.log( contains(txt, 'amet') )
// Preferred 2: Helper object
const UtilObj = {
contains(str: string, substr: string) {
return str.indexOf(substr) !== -1
}
};
console.log( UtilObj.contains(txt, 'Shrek') )
Further Reading
For more information on the topics from this lesson, please see the links below:
- Official TypeScript Documentation: Classes
- Mozilla Web Docs: Static methods
- KoderHQ: Static Class methods in Javascript
- Wikipedia: The Static keyword in programming
Summary: Points to remember
- A static class method belongs to a class, not an instance.
- A static method uses the static keyword when we define it.
- Static members can be encapsulated with the public , private and protected modifiers.
- We call a static method directly on the class, using the class name and dot notation. We don’t need to create an object instance.
- TypeScript does not allow more than one static method with the same name, the compiler will raise an error.
- Class properties can be marked as static , as well as encapsulated.
- Static members can only affect other static members.
- Instance objects cannot access static members and static methods cannnot access instance members.
- A static member’s this construct refers to the class, not the calling object.
- TypeScript doesn’t have static classes. Top-level functions and objects provide the same functionality.
- Static methods are typically used as helper, or utility methods.