Sunday, September 16, 2018

Typescript - Static keyword with Property,method,Constructor examples

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

Static keyword

static is a keyword which can be applied to 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 compilation error for 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, Compiler gives compilation error 'Static modifier cannot appear on a construct declaration'. In a Typescript, static keyword is not applied 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 different way using 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)

Related article


EmoticonEmoticon