Wednesday, November 14, 2018

TypeScript - Classes - Singleton pattern - read-only variables

In our previous blogpost, we saw the usage of private constructors:
https://sashankexpresstech.blogspot.com/2018/11/typescript-classes-singleton-pattern.html

To make a variable readonly, we assign the modifier readonly before it. By this the variable can be only read externally. But it cannot be assigned a value to. Consider the following example:

// Demo - readonly variables
class mySingleton {
private static instance: mySingleton;
public readonly name:string;

private constructor( name:string) {
this.name = name;
}

static getInstance() {
if (!mySingleton.instance) {
mySingleton.instance = new mySingleton("The Singleton Input");
}

return mySingleton.instance;
}
}

// Only One instance
let mySingletonInstance = mySingleton.getInstance();
console.log(mySingletonInstance.name);


In this example, we have assigned the readonly modifier to the variable name. Hence, we can only read the value in this variable. If we try to change the value in this variable, then we will receive a TypeScript error:

[ts] Cannot assign to 'name' because it is a constant or a read-only property.


Reference:

No comments:

Post a Comment