Typescript Static keyword to Property method and Constructor
- Admin
- Sep 20, 2023
- Typescript
In this blog post, We are going to learn Static keywords with properties, methods, and constructors of a class in typescript.
Static keyword in typescript
static
is a keyword that can be applied to the properties and methods of a class in typescript.
Static members are accessed using directly using class names.
Typescript static properties and Method example
When you want to call any methods in a class, we will use an object instance for accessing its methods, Static methods will use class names.
In class,
- Declared static variable and non-static variable
- Declared static method and non-static method
- static methods and properties are accessed using class names
- non-static methods and variables are accessed using an instance of a class ie an object.
It gives a compilation error for the below cases.
- calling a static method with an object or instance names
- calling non-static method with class names
class MyClass {
static staticVariable: number = 0;
nonStaticVariable: number = 0;
constructor() {
console.log("constructor");
}
nonStaticMethod() {
console.log("non static method");
}
static staticMethod() {
console.log("Static method");
}
}
MyClass.staticMethod(); // This works fine
let myclass1 = new MyClass();
myclass1.nonStaticMethod(); // This works fine
myclass1.staticMethod(); // Compilation Error
MyClass.nonStaticMethod(); // Compilation Error
Static Constructor typescript
when the static keyword is applied to the constructor, the Compiler gives the compilation error ’Static modifier cannot appear on a construct declaration’. In a Typescript, a static keyword does not apply to a class constructor.
class ClassDemo {
msg: string;
static constructor(msg: string) {
this.msg = message;
}
hello() {
return "Hello, " + this.msg;
}
}
let classDemo = new ClassDemo("world");
typescript static member variable and method Example
We can write a static keyword in a different way using the static method.
Declare static initialization method which will initialize data
class ClassDemo {
static msg: string;
constructor() {}
static construct() {
this.msg = "static typescript example";
console.log("construct static method");
}
}
console.log(ClassDemo.construct);