In TypeScript, static properties are properties that are associated with the class itself rather than with an instance of the class. Static properties are shared across all instances of the class and can be accessed using the class name directly, not via an instance.
Example: Static Properties
class Grid {
static origin = { x: 0, y: 0 }; // Static property shared across all instances
constructor(public scale: number) {}
calculateDistanceFromOrigin(point: { x: number; y: number }) {
let xDist = point.x - Grid.origin.x; // Accessing static property via class name
let yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({ x: 10, y: 10 })); // Calculate distance for grid1
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 })); // Calculate distance for grid2
Key Points:
- Static properties (e.g.,
static origin
) are associated with the class, not the instance. In the above example, theorigin
property is shared across all instances ofGrid
. - You can access static properties using the class name (
Grid.origin
), not an instance (grid1.origin
).
Example 2: Static Methods and Properties
class DemoCounter {
static counter: number = 0; // Static property shared by all instances
name: string = "";
increament(name: string): void {
DemoCounter.counter++; // Accessing static property via class name
this.name = name;
}
static doSomething(): void {
console.log("printing from static method");
}
}
let demoCounter: DemoCounter = new DemoCounter();
let demoCounter2: DemoCounter = new DemoCounter();
demoCounter.increament("x");
demoCounter.increament("y");
demoCounter2.increament("z");
console.log(DemoCounter.counter); // Static property accessed via class
console.log(demoCounter.name); // Instance property
console.log(demoCounter2.name); // Instance property
DemoCounter.doSomething(); // Calling static method directly via class
Key Points:
- Static methods (e.g.,
static doSomething()
) are methods that belong to the class itself, not instances of the class. - You can call static methods using the class name (
DemoCounter.doSomething()
), and they can access and modify static properties (DemoCounter.counter
). - Static properties are shared among all instances. In the example,
counter
is shared betweendemoCounter
anddemoCounter2
, so the value will accumulate across all instances.