How to access static properties in an object in TypeScript

1 Answer

0 votes
class Configuration {
    // Define a private static property with an explicit type (string)
    private static environment: string = "production";

    // A static method with explicit return type (string) to safely access the property
    public static getEnvironment(): string {
        // Use the class name to access static members internally
        return Configuration.environment;
    }

    // A static method with parameter typing (newEnv: string) and return type (void)
    public static setEnvironment(newEnv: string): void {
        if (newEnv && newEnv.trim() !== "") {
            Configuration.environment = newEnv;
        }
    }
}

// --- Example Usage ---

// 1. Accessing the static property/method directly via the Class Name (Best Practice)
console.log(`Current Environment: ${Configuration.getEnvironment()}`);

// 2. Modifying the static property via a typed static setter function
Configuration.setEnvironment("staging");
console.log(`Updated Environment: ${Configuration.getEnvironment()}`);

/* 
 * Note on Instances:
 * const configInstance = new Configuration();
 * console.log(configInstance.environment); // Error: Property 'environment' is a static member of class 'Configuration'
 */


/*
run:

Current Environment: production
Updated Environment: staging

*/

 



answered Oct 31 by avibootz
...