Static members
- TypeScript course
- Intermediate
- Lesson 4/89
- 4 min
Learn class-level members with static.
What is static?
Members defined with static belong to the class itself, not to instances. They are accessed directly with the class name, without creating an instance. For example MathUtil.PI and MathUtil.square(5).
class MathUtil {
static PI: number = 3.14;
static square(n: number): number {
return n * n;
}
}
console.log(MathUtil.PI);
console.log(MathUtil.square(5));Instance vs static
Instance members are accessed after creating an instance with new, while static members are accessed directly with the class name. To access a static field from inside an instance method, you use the class name.
class Counter {
static count: number = 0;
increment(): void {
Counter.count++;
}
}Practice Write a Counter class
Define a Counter class. Add a static count: number = 0 field and a static increment(): void method (the method increments Counter.count). Call Counter.increment() twice and print Counter.count.
Starter code
// Counter sınıfı tanımla
// count alanı sınıf düzeyinde, başlangıç 0
// increment metodu sınıf düzeyinde, count'u artırır
// increment'i iki kez çağır, count'u yazdırSample solution
class Counter {
static count: number = 0;
static increment(): void {
Counter.count++;
}
}
Counter.increment();
Counter.increment();
console.log(Counter.count);Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a static member accessed?
- First create an instance with new
- Directly with the class name Correct answer
- With super.
- With this.
Explanation: Static members are accessed directly with the class name without creating an instance: MathUtil.PI. this and super are used in an instance context; new creates an instance.
2 Complete the static keyword
class MathUtil {
____ PI: number = 3.14;
}
class MathUtil {
static PI: number = 3.14;
}
Explanation: static makes the member class-level. class is the wrong context, const is invalid in a class body, and public is an access modifier (it does not make it static).
3 Static member parts
| Term | Meaning |
|---|---|
static |
Class-level member |
MathUtil.PI |
Static field access |
MathUtil.square(5) |
Static method call |
Counter.count |
Access via class name |