Wednesday, November 14, 2018

TypeScript - Classes - static properties and methods

When we create a class, we cannot use its properties and methods without instantiating the class.

// Static Properties and Methods
class miscItems {
E: number = 2.718;
calcMultipleE(inputMultiple:number) : number{
return this.E * inputMultiple;
}
}

But, TypeScript provides a facility to access the methods and properties without instantiating it by using the static keyword. Observe how we convert the above class to be able to hold static properties and methods and then access it directly. Consider the below rewritten code:

// Static Properties and Methods
class miscItems {
static E: number = 2.718;
static calcMultipleE(inputMultiple:number) : number{
return this.E * inputMultiple;
}
}

console.log(2*miscItems.E);
console.log(miscItems.calcMultipleE(8));

Let us now, compile the code

$ tsc
$

check the console output:

5.436
21.744

We are able to access static properties and methods  defined in a class without instantiating it.

Reference:

No comments:

Post a Comment