×
☰ See All Chapters

TypeScript Static Members

Static properties are also called class properties or class variables. If a property's value never changes, it should be declared as static to ensure that it won't be redefined for each instance. If a property's value only changes when the constructor is called and doesn't depend on the instance, it should be made static. Static members can assess only static members, but static members can be accessed by any one.

Static Properties

Properties can be made static by preceding the declaration with the static keyword. Visibility of static variables is similar to instance variables which depend on the access specifiers. However, most static variables are declared public since they must be available for users of the class. Static variables can be accessed by calling with the class name as below:

className.variableName

Example

class Test {

    static fullName = "Manu Manjunatha";

    static message = "Hello";

    finalMessage: string;

    constructor( greet: string ) {

        this.finalMessage = Test.message + Test.fullName + greet

    }

}

 

let fullName: string = Test.fullName;

Static Methods

Methods can be made static by preceding the declaration with the static keyword. Static methods are invoked through the class name, not through an instance, can be accessed by calling with the class name as below:

className.methodName();

Example

class Test {

    static getFullName(firstName: string, lastName: string): string {

            return firstName + " " +  lastName;

    }

}

let fullName: string = Test.getFullName("Manu" , "Manjunatha");

 


All Chapters
Author