{

Typescript Static keyword with Property,method,Constructor


In this blog post, We are going to learn Static keyword with properties, methods, and constructors of a class in typescript.
Typescript - Static keyword with Property,method,Constructor examples

Static keyword

static is a keyword that can be applied to the properties and methods of a class. Static members are accessed using directly using class names.

static properties and Method example

When you want to call any methods in a class, we will use object instance for accessing it methods, Static methods will use class names.

In the class,

  • Declared static variable and nonstatic variable
  • Declared static method and nonstatic method
  • static methods and properties are accessed using class names
  • nonstatic methods and variables are accessed using an instance of a class ie 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

when the static keyword is applied to the constructor, the Compiler gives 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");  

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)  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.